一、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)
訪問網站:
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/download/1597310075.png
查看圖片
http://127.0.0.1:5000/show/1597309506.png