美文网首页
flask 上传文件

flask 上传文件

作者: Benny_浩 | 来源:发表于2017-11-22 22:42 被阅读645次

werkzeug库可以判断文件名是否安全,例如防止文件名是../../../a.png,安装这个库:

pip install werkzeug
from flask import Flask,request,render_template
from werkzeug.utils import secure_filename
import os

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'static/uploads/'  #在static文件夹下创建uploads文件夹
app.config['ALLOWED_EXTENSIONS'] = set(['png', 'jpg', 'jpeg', 'gif'])
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 #16MB  限制文件大小

# For a given file, return whether it's an allowed type or not
def allowed_file(filename):
    '''判断filename是否有后缀以及后缀是否在app.config['ALLOWED_EXTENSIONS']中'''
    return '.' in filename and filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']

@app.route('/')
def hello_world():
    return 'hello world'

@app.route('/upload/', methods=['POST'])
def upload():
    upload_file = request.files['image01']
    if upload_file and allowed_file(upload_file.filename):
        filename = secure_filename(upload_file.filename)
        upload_file.save(os.path.join(app.root_path, app.config['UPLOAD_FOLDER'], filename)) #app.root_path获取当前项目绝对路径
        file_content = request.files['image01']
        print(file_content.stream.read())
        print('type',type(file_content)) #<class 'werkzeug.datastructures.FileStorage'>
        print('aaa')
        return 'hello, ' + request.form.get('name', 'little apple') + '. success'
    else:
        return 'hello, ' + request.form.get('name', 'little apple') + '. failed'

if __name__ == '__main__':
    app.run(debug=True)

测试代码

import requests

files = {'image01': open('01.jpg', 'rb')}  
user_info = {'name': 'letian'}  
r = requests.post("http://127.0.0.1:5000/upload/", data=user_info, files=files)

print(r.text)  #hello, letian. success

upload_file.stream.read()  #读取文件内容
len(upload_file.read()) #读取文件大小

问题,获取的文件经过一次.read()以后指针到最后,无法进行下一步操作。

相关文章

网友评论

      本文标题:flask 上传文件

      本文链接:https://www.haomeiwen.com/subject/ccxavxtx.html