文件上传本文采用两种方式。首先form表单要设置属性:enctype="multipart/form-data"。首先讲第一种方式,这种方式有点小问题,上传中文文件文件名会出错。
先看第一种方法
首先初始化一些参数之类的:
from werkzeug.utils import secure_filename
import os
UPLOAD_FOLDER = 'D:\Demo\demo'#定义上传路径
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])#上传文件的格式
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER#设置上传文件路径,文件夹
那个secure_filename
干嘛的呢?文档中这么说的:
Pass it a filename and it will return a secure version of it. This filename can then safely be stored on a regular file system and passed to os.path.join(). The filename returned is an ASCII only string for maximum portability.
On windows systems the function also makes sure that the file is not named after one of the special device files.
>>> secure_filename("My cool movie.mov")
'My_cool_movie.mov'
>>> secure_filename("../../../etc/passwd")
'etc_passwd'
>>> secure_filename(u'i contain cool \xfcml\xe4uts.txt')
'i_contain_cool_umlauts.txt'
The function might return an empty filename. It’s your responsibility to ensure that the filename is unique and that you generate random filename if the function returned an empty one.
New in version 0.5.
Parameters: filename – the filename to secure
接下面我们将来检查上传至服务器的文件的格式
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
然后就是上传函数了:
@app.route('/upload',methods=['GET','POST'])
def upload():
if request.method == 'POST':
file = request.files['img']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return file.filename
return render_template('upload.html')
就这样完成了上传功能。
接下来将第二种方法:
还是首先初始化:
from flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class
from flask_wtf.file import FileField, FileRequired, FileAllowed
app = Flask(__name__)
app.config['SECRET_KEY'] = 'I have a dream'
app.config['UPLOADED_IMAGES_DEST'] = os.path.dirname(__file__)+'/uploads'
images = UploadSet('images', IMAGES)
configure_uploads(app, images)
patch_request_class(app)
然后使用WTF表单写上传表单:
class UploadForm(FlaskForm):
image = FileField('选择上传的文件',validators=[
FileAllowed(images, '只能上传图片!'),
FileRequired('文件未选择!')])
submit = SubmitField('上传')
html页:
<form method="POST" enctype="multipart/form-data">
{{ form.csrf_token }}
{{ form.image.label }}
{{ form.image }}
{% for error in form.image.errors %}
<span style="color: red;">{{ error }}</span>
{% endfor %}
{{ form.submit }}
</form>
然后就是上传函数了
@app.route('/upload',methods=['GET','POST'])
def upload():
form = UploadForm()
if form.validate_on_submit():
filename = images.save(form.image.data)
file_url = images.url(filename)
return '上传成功,路径:'+file_url+'<br><img src="'+file_url+'" width="200px">'
return render_template('upload.html',form=form,title='文件上传')
最后上传成功的截图。妹纸漂亮吧 (^._.^)ノ
评论
2