Flask 简明教程
Flask – File Uploading
在 Flask 中处理文件上传非常容易。它需要一个将 enctype 属性设置为“multipart/form-data”的 HTML 表单,将文件发布到 URL。URL 处理程序从 request.files[] 对象获取文件并将其保存到所需位置。
Handling file upload in Flask is very easy. It needs an HTML form with its enctype attribute set to ‘multipart/form-data’, posting the file to a URL. The URL handler fetches file from request.files[] object and saves it to the desired location.
每个上传的文件首先保存在服务器上的临时位置,然后才实际保存到其最终位置。目标文件的文件名可以硬编码,也可以从 request.files[file] 对象的 filename 属性获取。但是,建议使用 secure_filename() 函数获取其安全版本。
Each uploaded file is first saved in a temporary location on the server, before it is actually saved to its ultimate location. Name of destination file can be hard-coded or can be obtained from filename property of request.files[file] object. However, it is recommended to obtain a secure version of it using the secure_filename() function.
可以在 Flask 对象的配置设置中定义默认上传文件夹的路径和上传文件的大小。
It is possible to define the path of default upload folder and maximum size of uploaded file in configuration settings of Flask object.
app.config[‘UPLOAD_FOLDER’] |
Defines path for upload folder |
app.config[‘MAX_CONTENT_PATH’] |
Specifies maximum size of file yo be uploaded – in bytes |
以下代码具有 ‘/upload’ URL 规则,用于显示模板文件夹中的 ‘upload.html’ ,以及 ‘/upload-file’ URL 规则,用于调用 uploader() 函数处理上传过程。
The following code has ‘/upload’ URL rule that displays ‘upload.html’ from the templates folder, and ‘/upload-file’ URL rule that calls uploader() function handling upload process.
‘upload.html’ 有一个文件选择器按钮和一个提交按钮。
‘upload.html’ has a file chooser button and a submit button.
<html>
<body>
<form action = "http://localhost:5000/uploader" method = "POST"
enctype = "multipart/form-data">
<input type = "file" name = "file" />
<input type = "submit"/>
</form>
</body>
</html>
您将看到如下所示的屏幕。
You will see the screen as shown below.
选择文件后单击 Submit 。表单的 post 方法调用 ‘/upload_file’ URL。基础函数 uploader() 执行保存操作。
Click Submit after choosing file. Form’s post method invokes ‘/upload_file’ URL. The underlying function uploader() does the save operation.
下面是 Flask 应用程序的 Python 代码。
Following is the Python code of Flask application.
from flask import Flask, render_template, request
from werkzeug import secure_filename
app = Flask(__name__)
@app.route('/upload')
def upload_file():
return render_template('upload.html')
@app.route('/uploader', methods = ['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['file']
f.save(secure_filename(f.filename))
return 'file uploaded successfully'
if __name__ == '__main__':
app.run(debug = True)