In Flask, How Do I Store A User Submitted File Temporarily To Manipulate It And Return It Back?
So I've been working on a Flask application where the user submits a file to a form, the server takes it and manipulates it, then returns the edited file back to the user. I am new
Solution 1:
In Flask official documentation site, there is a file uploader example as below:
@app.route('/', methods=['GET', 'POST'])defupload_file():
if request.method == 'POST':
# check if the post request has the file partif'file'notin request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
# If the user does not select a file, the browser submits an# empty file without a filename.if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('download_file', name=filename))
return'''
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form method=post enctype=multipart/form-data>
<input type=file name=file>
<input type=submit value=Upload>
</form>
'''
Here is how you can get the file content: file = request.files['file']
and of course you can do further manipulation on the file.
Here is how you can save the file file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
. It's really up to you if you want to save the file and return the file later or just modify it in memory and return it immediately.
Post a Comment for "In Flask, How Do I Store A User Submitted File Temporarily To Manipulate It And Return It Back?"