1.文件目录如下: 一定要新建那个 upload 文件保存文件夹,保存时会报错
2. 代码:
upload.html
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form action="http://localhost:5000/uploader" method="POST" enctype="multipart/form-data">
<input type="file" name="file" accept=".jpg,.png" />
<input type="submit" />
</form>
</body>
</html>
2.test.py
from flask import Flask, render_template, request
from werkzeug.utils import secure_filename
import os
app = Flask(__name__,template_folder= 'template')
#配置上传文件的存储路径
app.config['UPLOAD_FOLDER'] = 'upload/'
@app.route('/')
def upload_file():
return render_template('upload.html')
@app.route('/uploader', methods = ['GET', 'POST'])
def uploader():
if request.method == 'POST':
f = request.files['file']
f.save(os.path.join(app.config['UPLOAD_FOLDER'],secure_filename(f.filename)))
return 'file uploaded successfully'
if __name__ == '__main__':
app.run()
3.运行后,浏览器输入http://127.0.0.1:5000/ 选择一个文件,然后点击上传,出现
说明上传成功了,然后去upload文件夹查看,上传的文件的确出现在了upload 文件夹下