main.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import os
  2. #import magic
  3. import urllib.request
  4. from app import app
  5. from flask import Flask, flash, request, redirect, render_template, jsonify
  6. from werkzeug.utils import secure_filename
  7. ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
  8. def allowed_file(filename):
  9. return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
  10. @app.route('/')
  11. def upload_form():
  12. return render_template('file-upload.html')
  13. @app.route('/python-flask-files-upload', methods=['POST'])
  14. def upload_file():
  15. # check if the post request has the file part
  16. if 'files[]' not in request.files:
  17. resp = jsonify({'message' : 'No file part in the request'})
  18. resp.status_code = 400
  19. return resp
  20. files = request.files.getlist('files[]')
  21. errors = {}
  22. success = False
  23. for file in files:
  24. if file and allowed_file(file.filename):
  25. filename = secure_filename(file.filename)
  26. file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
  27. success = True
  28. else:
  29. errors[file.filename] = 'File type is not allowed'
  30. if success and errors:
  31. errors['message'] = 'File(s) successfully uploaded'
  32. resp = jsonify(errors)
  33. resp.status_code = 206
  34. return resp
  35. if success:
  36. resp = jsonify({'message' : 'Files successfully uploaded'})
  37. resp.status_code = 201
  38. return resp
  39. else:
  40. resp = jsonify(errors)
  41. resp.status_code = 400
  42. return resp
  43. if __name__ == "__main__":
  44. app.run()