Flask + jQuery 实现异步上传图片文件
Flask框架作为后端,bootstrap+jQuery作为前端。jQuery将前端选择的图片异步post,后端接收到图片后保存到本地。
1,jQuery处理的部分
先看用到html代码:
<input id="img_name" type="text"/>
<input id="img_file" type="file"/>
<input id="btn" type="button" onclick="fun_post_img()">上传图片</span>
fun_post_img 方法代码(上传图片,同时指定上传的图片名):
function fun_new_brand(){
let data = new FormData();
data.append("img", $("#img_file")[0].files[0]);
data.append("name", $("#img_name").val())
$.ajax({
url: "/post/img",
data: data,
type: "POST",
async: true,
cache: false,
processData: false,
contentType: false,
success: function (data){
alert(data);
}
});
}
html代码说明:
▪ 指定上传图片的图片名
<input id="img_name" type="text"/>
▪ 选择要上传的图片
<input id="img_file" type="file"/>
如果要对文件类型和文件大小进行判断,自行处理,这里不赘述。
js代码说明:
通过 jQuery 的 ajax 方法提交数据,需要在 ajax 中指明 ajax 类型为 post。
▪ async 参数
async 参数设置成true,表示在请求开始后,其他代码依然能够执行。
async 参数设置成false,表示在请求开始后,其他代码要等待该请求完成。
▪ cache 参数
是否在将数据缓存。当发起一次请求后,会把获得的结果以缓存的形式进行存储,当再次发起请求时,如果 cache 的值是 true ,那么会直接从缓存中读取,而不是再次发起一个请求了。
▪ processData 参数
默认情况下,processData 的值是 true,其代表以对象的形式上传的数据都会被转换为字符串的形式上传。而当上传文件的时候,则不需要把其转换为字符串,因此要改成false
▪ contentType 参数
contentType 发送信息至服务器时内容编码类型(告诉服务器从浏览器提交过来的数据格式),默认值为contentType = "application/x-www-form-urlencoded"。
在 ajax 中 contentType 设置为 false 是为了避免 JQuery 对其操作,从而失去分界符,而使服务器不能正常解析文件。
2,Flask 后端处理部分
from flask import request
import os
@index_app.route("/post/img", methods=['POST'])
def ajax_post_img():
img_file = request.files['img']
img_name = request.form["name"]
# 获取当前文件所在路径
current_path = os.path.dirname(__file__)
# 图片存储路径
img_path = "{}/pic".format(base_path)
# 判断文件夹是否存在
if not os.path.exists(img_path):
os.mkdir(img_path)
logo_file.save("{}/{}.jpg".format(img_path, img_name))
return "1"
注意,必须在路由中指定 metohds 为 POST
图片文件和图片名数据类型不同,图片文件需要使用 request.files 来获取,而文件名是字符串类型,使用 request.form 来获取。
我的笔记