Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit b7cf541

Browse files
authored
Add files via upload
1 parent 8e93fff commit b7cf541

File tree

3 files changed

+57
-0
lines changed

3 files changed

+57
-0
lines changed
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
from flask import Flask
2+
3+
UPLOAD_FOLDER = 'C:/uploads'
4+
5+
app = Flask(__name__)
6+
#app.secret_key = "secret key"
7+
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
8+
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import os
2+
import urllib.request
3+
from app import app
4+
from flask import Flask, request, redirect, jsonify
5+
from werkzeug.utils import secure_filename
6+
7+
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
8+
9+
def allowed_file(filename):
10+
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
11+
12+
@app.route('/multiple-files-upload', methods=['POST'])
13+
def upload_file():
14+
# check if the post request has the file part
15+
if 'files[]' not in request.files:
16+
resp = jsonify({'message' : 'No file part in the request'})
17+
resp.status_code = 400
18+
return resp
19+
20+
files = request.files.getlist('files[]')
21+
22+
errors = {}
23+
success = False
24+
25+
for file in files:
26+
if file and allowed_file(file.filename):
27+
filename = secure_filename(file.filename)
28+
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
29+
success = True
30+
else:
31+
errors[file.filename] = 'File type is not allowed'
32+
33+
if success and errors:
34+
errors['message'] = 'File(s) successfully uploaded'
35+
resp = jsonify(errors)
36+
resp.status_code = 206
37+
return resp
38+
if success:
39+
resp = jsonify({'message' : 'Files successfully uploaded'})
40+
resp.status_code = 201
41+
return resp
42+
else:
43+
resp = jsonify(errors)
44+
resp.status_code = 400
45+
return resp
46+
47+
if __name__ == "__main__":
48+
app.run()
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
You can read tutorial https://www.roytuts.com/python-flask-rest-api-multiple-files-upload/

0 commit comments

Comments
 (0)