Flask 原生方法上传文件
2020-07-02 本文已影响0人
SingleDiego
文档:https://flask.palletsprojects.com/en/1.1.x/patterns/fileuploads/
参考:https://zhuanlan.zhihu.com/p/23731819?refer=flask
原生方法
- 创建用于上传的 HTML 表单,
<form>
标签的enctype
属性设为multipart/form-data
,并且在里面包含一个<input type=file>
标签。
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
- 在浏览器选择文件并点击上传按钮后,就通过
request
对象获取文件,因为上传文件那个<input>
标签的name
属性设为了file
,所以我们先在也有file
这个key
获取文件:
file = request.files['file']
- 使用
save
方法保存文件:
file.save(path + filename)
一个完整例子:
@app.route('/upload', methods=['GET', 'POST'])
def upload():
path = './upload/'
if request.method == 'POST':
file = request.files['file']
file.save(path + file.filename)
return render_template('upload-page.html')
上传配置
下面的例子演示了如何使用配置和如何确保上传文件的安全性。UPLOAD_FOLDER
是文件上传目录,ALLOWED_EXTENSIONS
是允许上传的文件后缀名,可以看到,它们并不会直接起作用,我们还是需要编写相关的函数和变量来使用它。werkzeug
库的 secure_filename
方法则可保证文件名的安全。
from flask import (
Flask,
render_template,
request,
redirect,
url_for
)
import os
from werkzeug.utils import secure_filename
# 部分代表省略
app.config['UPLOAD_FOLDER'] = './upload/'
app.config['ALLOWED_EXTENSIONS'] = set(['txt', 'jpg'])
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() \
in app.config['ALLOWED_EXTENSIONS']
@app.route('/upload', methods=['GET', 'POST'])
def upload():
path = './upload/'
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
# if user does not select file, browser also
# submit an empty part without filename
if file.filename == '':
flash('No selected file')
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
return redirect(url_for('upload'))
return render_template('upload-page.html')
获取上传后的文件
配置一个函数来获取上传文件的 url
:
from flask import send_from_directory
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename)
获取 url
:
file_url = url_for('uploaded_file', filename=filename)