python
from flask import Flask, request, render_template,redirect, url_for
from werkzeug.utils import secure_filename
import os
from flask import send_from_directory # send_from_directory可以从目录加载文件
app = Flask(__name__)
#UPLOAD_FOLDER = 'media' # 注意:要提前在根目录下新建media文件,否则会报错
'''
报错路径找不到:
要解决此问题,可以将反斜杠替换为正斜杠,或者使用原始字符串字面值指定文件路径.
通过在字符串前添加r,它就变成了一个原始字符串文字,并且反斜杠将被解释为文字反斜杠而不是转义字符。
'''
#UPLOAD_FOLDER = 'D:\pythonXangmu\pythonproject01\flask\caiquan2\media'
UPLOAD_FOLDER = r'D:\pythonXangmu\pythonproject01\flask\caiquan2\media'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER # UPLOAD FOLDER 英文上传文件夹
# 判断上传的文件是否是允许的后缀
def allowed_file(filename):
return "." in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS#把.
@app.route('/')
def index():
return render_template('upload.html')
@app.route('/center/upload',methods=['POST'])#对应表单里面的action="/upload"
def center():
if "file" not in request.files: #"file" 对应前端upload.html 中的name
return redirect(request.url)#redirect 重定向新的地址
file = request.files.get('file') # 获取文件
if not allowed_file(file.filename): #如果不是传入的指定格式文件。重定向到当前url
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename) # 用这个函数确定文件名称是否是安全
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) # 保存文件 os.path.join把目录和文件名合成一个路径
return redirect(url_for('show', filename=filename))
# 展示
@app.route('/show/<filename>')
def show(filename):
# send_from_directory可以从目录加载文件
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
upload.html
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文件上传</title>
</head>
<body>
<form action="/center/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="提交">
</form>
</body>
</html>