如何在flask中实现文件的上传呢?
首先请看templates中的html模板
特别要注意,模板中必须要使用 enctype="multipart/form-data" , 否则form不会做任何事情
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<p>
<input type="file" name="file">
<input type =submit value="upload">
</p>
</form>
</body>
</html>
使用request.files 模块实现文件上传
并使用os中的path
from flask import Flask, request,make_response,render_template, redirect, url_for
from werkzeug.utils import secure_filename # 使用这个是为了确保filename是安全的
from os import path
实现代码
@app.route("/upload",methods=['GET','POST'])
def upload():
if request.method=='POST':
f = request.files["file"]
base_path = path.abspath(path.dirname(__file__))
upload_path = path.join(base_path,'static/uploads/')
file_name = upload_path + secure_filename(f.filename)
f.save(file_name)
return redirect(url_for('upload'))
return render_template('upload.html')
初次执行代码前,需要手动在static目录下创建uploads目录