Python-Flask-文件上传

一、Python-Flask-文件上传

1、简化版文件上传

创建目录:

cd 5-4 
mkdir -p uploads   #必须先创建uploads文件夹。

upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>文件上传示例</h1>
    <form action="" enctype='multipart/form-data' method='POST'>
        <input type="file" name="file">
        <input type="submit" value="上传">
    </form>
</body>
</html>

app.py

import os
from flask import Flask, render_template, send_from_directory, request, jsonify, make_response
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/<path:filename>")
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/<string:filename>', 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:
pass


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

访问网站:

http://127.0.0.1:5000/upload

 

2、优化版文件上传

 

2.1. 自动创建upload文件夹。

upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<h1>上传文件</h1>
<body>
<form id="form1" method="post" action="/api/upload" enctype="multipart/form-data">
    <div>
        <input id="File1" type="file" name="myfile"/>  <!--后台代码中获取文件是通过form的name来标识的-->
        <input type="submit">提交</input>
    </div>
</form>
</body>
</html>

app.py

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/<path:filename>")
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/

 

上传成功,返回值

 

 

 下载文件

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

 查看图片

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

 

posted @ 2020-08-13 16:41  努力哥  阅读(5068)  评论(0编辑  收藏  举报