Skip to content

Instantly share code, notes, and snippets.

@fredrikbonander
Last active January 4, 2016 08:19
Show Gist options
  • Save fredrikbonander/8594759 to your computer and use it in GitHub Desktop.
Save fredrikbonander/8594759 to your computer and use it in GitHub Desktop.
Flask fileupoad
import os
import uuid
from flask import Flask
from flask import jsonify
from flask import request
from flask import make_response
from werkzeug import secure_filename
UPLOAD_FOLDER = os.path.dirname(os.path.realpath(__file__))
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
@app.route('/tmp/upload', methods=['GET', 'POST', 'OPTIONS'])
def dispatcher():
if request.method == 'OPTIONS':
return make_response('', 204, {
'Access-Control-Allow-Origin': '*'
})
index = 0
filename = ''
file_blob = request.files.get('file%s' % index, False)
while file_blob:
if allowed_file(file_blob.filename):
filename = '%s-%s' % (uuid.uuid4(), secure_filename(file_blob.filename))
file_blob.save(os.path.join(app.config['UPLOAD_FOLDER'], 'upload', filename))
index += 1
file_blob = request.files.get('file%s' % index, False)
response = {'file':filename}
print response
return make_response(jsonify(response), 201, {
'Access-Control-Allow-Origin': '*'
})
if __name__ == "__main__":
app.debug = True
app.run(port=8090)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment