Flask 之 secure_filename
from flask import Flask, redirect, request, render_template, url_for, send_from_directory from werkzeug.utils import secure_filename import os app = Flask(__name__) '''配置文件路径, 防止恶意读取你文件的''' app.config['UPLOAD_FOLDER'] = 'C:/Users/Administrator/Desktop/flask/uploads/' ''' 设置上传文件大小 ''' app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024 ''' 文件上传 三要素 - 表单提交是POST 的请求 - 表单 写入参数 enctype='multipart/form-data' 当上传内容非文本(MP3。MP4。。。)时候,如图片。需要将表单的设置成enctype编码格式 - 使用上传属性 file ''' ''' filename 获得上传文件名,secure_filename函数获得安全文件名,防止客户端伪造文件 ''' @app.route('/upload_file') def index(): return render_template('upload_file.html') ''' 普通文件上传 ''' # @app.route('/upload_file', methods=['GET', 'POST']) # def upload_file(): # if request.method == 'POST': # f = request.files.get('myfile') # # f.save(secure_filename(f.filename)) # # return Response('文件上传成功') ''' 存储安全路径上传 ''' # @app.route('/upload_file', methods=['GET', 'POST']) # def upload_file(): # if request.method == 'POST': # f = request.files.get('myfile') # # '''这个是文件名称''' # filename = secure_filename(f.filename) # # '''将文件夹和文件名连接在一起''' # f.save(os.path.join(app.config['UPLOAD_FOLDER'] + filename)) # # # return Response('文件上传成功') ''' 展示你上传的图片。。 ''' @app.route('/upload_file', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': f = request.files.get('myfile') '''这个是文件名称''' filename = secure_filename(f.filename) '''将文件夹和文件名连接在一起''' f.save(os.path.join(app.config['UPLOAD_FOLDER'] + filename)) return redirect(url_for('show_image', filename=filename)) @app.route('/show_image/<filename>') def show_image(filename): '''send_from_directory 这是 接口返回真实的文件,就是帮你找到你的所需要的文件''' return send_from_directory(app.config['UPLOAD_FOLDER'],filename) if __name__ == '__main__': app.run(debug=True)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>UPLOAD FILE</title> </head> <body> <form action="" method="post" enctype="multipart/form-data"> <input type="file" name="myfile"> <button type="submit">上传</button> </form> </body> </html>