Python-Flask-文件上传

一、Python-Flask-文件上传

1、简化版文件上传

Python-Flask-文件上传

创建目录:

python;gutter:false; cd 5-4 mkdir -p uploads #必须先创建uploads文件夹。</p> <pre><code> upload.html ;gutter:false;
Title

文件上传示例

app.py

import osfrom flask import Flask, render_template, send_from_directory, request, jsonify, make_responseimport timeapp = Flask(__name__)UPLOAD_FOLDER = 'upload'app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER  # 设置文件上传的目标文件夹basedir = os.path.abspath(os.path.dirname(__file__))  # 获取当前项目的绝对路径ALLOWED_EXTENSIONS = set(['txt', 'png', 'jpg', 'xls', 'JPG', 'PNG', 'xlsx', 'gif', 'GIF'])  # 允许上传的文件后缀# 判断文件是否合法def allowed_file(filename):    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS# 具有上传功能的页面@app.route('/')def upload_test():    return render_template('upload.html')@app.route('/api/upload', methods=['POST'], strict_slashes=False)def api_upload():    file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER'])  # 拼接成合法文件夹地址    if not os.path.exists(file_dir):        os.makedirs(file_dir)  # 文件夹不存在就创建    f = request.files['myfile']  # 从表单的file字段获取文件,myfile为该表单的name值    if f and allowed_file(f.filename):  # 判断是否是允许上传的文件类型        fname = f.filename        ext = fname.rsplit('.', 1)[1]  # 获取文件后缀        unix_time = int(time.time())        new_filename = str(unix_time) + '.' + ext  # 修改文件名        f.save(os.path.join(file_dir, new_filename))  # 保存文件到upload目录        return jsonify({"errno": 0, "errmsg": "上传成功"})    else:        return jsonify({"errno": 1001, "errmsg": "上传失败"})# file download@app.route("/download/")def downloader(filename):    dirpath = os.path.join(app.root_path, 'upload')  # 这里是下在目录,从工程的根目录写起,比如你要下载static/js里面的js文件,这里就要写"static/js"    # return send_from_directory(dirpath, filename, as_attachment=False)  # as_attachment=True 一定要写,不然会变成打开,而不是下载    return send_from_directory(dirpath, filename, as_attachment=True)  # as_attachment=True  下载# show photo@app.route('/show/', methods=['GET'])def show_photo(filename):    file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER'])    if request.method == 'GET':        if filename is None:            pass        else:            image_data = open(os.path.join(file_dir, '%s' % filename), "rb").read()            response = make_response(image_data)            response.headers['Content-Type'] = 'image/png'            return response    else:        passif __name__ == '__main__':    app.run(debug=True)

访问网站:

http://127.0.0.1:5000/upload

Python-Flask-文件上传

2、优化版文件上传

Python-Flask-文件上传

2.1. 自动创建upload文件夹。

upload.html

html;gutter:false; Title</p> <p>上传文件</p> <pre><code> 提交 </code></pre> <pre><code> app.py ;gutter:false;
import os
from flask import Flask, render_template, send_from_directory, request, jsonify
import time

app = Flask(__name__)

UPLOAD_FOLDER = ‘upload’
app.config[‘UPLOAD_FOLDER’] = UPLOAD_FOLDER # 设置文件上传的目标文件夹
basedir = os.path.abspath(os.path.dirname(__file__)) # 获取当前项目的绝对路径
ALLOWED_EXTENSIONS = set([‘txt’, ‘png’, ‘jpg’, ‘xls’, ‘JPG’, ‘PNG’, ‘xlsx’, ‘gif’, ‘GIF’]) # 允许上传的文件后缀

# 判断文件是否合法
def allowed_file(filename):
return ‘.’ in filename and filename.rsplit(‘.’, 1)[1] in ALLOWED_EXTENSIONS

# 具有上传功能的页面
@app.route(‘/’)
def upload_test():
return render_template(‘upload.html’)

@app.route(‘/api/upload’, methods=[‘POST’], strict_slashes=False)
def api_upload():
file_dir = os.path.join(basedir, app.config[‘UPLOAD_FOLDER’]) # 拼接成合法文件夹地址
if not os.path.exists(file_dir):
os.makedirs(file_dir) # 文件夹不存在就创建
f = request.files[‘myfile’] # 从表单的file字段获取文件,myfile为该表单的name值
if f and allowed_file(f.filename): # 判断是否是允许上传的文件类型
fname = f.filename
ext = fname.rsplit(‘.’, 1)[1] # 获取文件后缀
unix_time = int(time.time())
new_filename = str(unix_time) + ‘.’ + ext # 修改文件名
f.save(os.path.join(file_dir, new_filename)) # 保存文件到upload目录
return jsonify({"errno": 0, "errmsg": "上传成功"})
else:
return jsonify({"errno": 1001, "errmsg": "上传失败"})

# file download
@app.route("/download/")
def downloader(filename):
dirpath = os.path.join(app.root_path, ‘upload’) # 这里是下在目录,从工程的根目录写起,比如你要下载static/js里面的js文件,这里就要写"static/js"
# return send_from_directory(dirpath, filename, as_attachment=False) # as_attachment=True 一定要写,不然会变成打开,而不是下载
return send_from_directory(dirpath, filename, as_attachment=True) # as_attachment=True 下载

if __name__ == ‘__main__’:
app.run(debug=True)访

1.2.访问网址

http://127.0.0.1:5000/

Python-Flask-文件上传

上传成功,返回值

Python-Flask-文件上传

下载文件

http://127.0.0.1:5000/download/1597310075.png

Python-Flask-文件上传

查看图片

http://127.0.0.1:5000/show/1597309506.png

Python-Flask-文件上传

Original: https://www.cnblogs.com/nulige/p/13497254.html
Author: 努力哥
Title: Python-Flask-文件上传

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/9260/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

发表回复

登录后才能评论
免费咨询
免费咨询
扫码关注
扫码关注
联系站长

站长Johngo!

大数据和算法重度研究者!

持续产出大数据、算法、LeetCode干货,以及业界好资源!

2022012703491714

微信来撩,免费咨询:xiaozhu_tec

分享本页
返回顶部