1.

How to upload files in the Flask application?

Answer»

Flask makes it simple to manage uploaded files. Just remember to include the enctype="multipart/form-data" tag in your HTML form, or the browser will refuse to send your files. Uploaded files are kept in memory or on the filesystem in a temporary place. You may get to those files by looking at the request object's files attribute. Each file that is uploaded is saved in that dictionary. It has the same behavior as a typical Python file object, but it additionally provides a save() method that allows you to save the file to the server's filesystem. Here's a simple example to demonstrate how it works:

from flask IMPORT request[Text WRAPPING Break][Text Wrapping Break]@app.route('/upload', methods=['GET', 'POST'])[Text Wrapping Break]DEF upload_file():[Text Wrapping Break]    if request.method == 'POST':[Text Wrapping Break]        f = request.files['the_file'][Text Wrapping Break]        f.save('/var/www/uploads/uploaded_file.txt')

The filename attribute can be used to determine how the file was named on the client before it was uploaded to your application. However, keep in mind that its value might be FAKED, so don't put your faith in it. If you WISH to utilize the client's filename to store the file on the server, you can use the secure filename() function that Werkzeug provides:

from werkzeug.utils import secure_filename[Text Wrapping Break][Text Wrapping Break]@app.route('/upload', methods=['GET', 'POST'])[Text Wrapping Break]def upload_file():[Text Wrapping Break]    if request.method == 'POST':[Text Wrapping Break]        file = request.files['the_file'][Text Wrapping Break]        file.save(f"/var/www/uploads/{secure_filename(file.filename)}")


Discussion

No Comment Found