利用ajax将前端上传的图片传至后端并保存到当前项目路径(Django项目)
1.对应的HTML代码
<button type="button" id="upload">预测</button>
<p>result: <span id='result'></span></p>
<div style="position: absolute;top: 20%;left: 15%">
<a href=":javascript" class="file"><input type="file" name="file" id="Images" multiple="multiple" accept="image/*" />点击这里上传图片
</a>
<div id="picViewsBox" style="width: 500px;height: 500px;color: #747171;border: 1px solid #8b8a8a;"><p style="text-align: center;margin-top: 50%">选择想要预测的图片</p></div>
</div>
2.对应的js代码
//利用ajax获取上传图片信息,而且不刷新当前页面
$(document).ready(function () {
//jq的处理函数,当点击提交按钮时执行。
$("#upload").click(function () {
var data = new FormData();
var len = $('#Images')[0].files.length;
for(var i =0;i<len;i++) {
var file = $('#Images')[0].files[i];
data.append('files', file);//将图片信息file保存到该对象
};
if (len==0){
alert("未上传图片!");
}
else {
$.ajax({
url:'http://127.0.0.1:8000/get_picture_message/',
type:'POST',
data:data,
processData:false,//建议添加,否则值传可能不到对应url
contentType:false,//建议添加,否则值可能传不到对应url
success:function(arg){
console.log(arg);
$('#result').html(arg)
},
error:function(arg){
console.log(arg);
$('#result').html(arg);
alert("失败")
}
});
}
});
});
3.后端代码
import os
from Rock_Intelligence_analysis import settings
from django.http import HttpResponse
def get_picture_message(request):
if request.method == 'POST':
files = request.FILES.getlist('files')#获取ajax传过来的myfiles值,类型为list
#遍历list对象files,当选择多张图片时实现遍历保存图片
for f in files:
print(f.name)
img_name = f'{f.name}' # 重命图片名及格式
print("名称:",img_name)
img_path = os.path.join(settings.IMG_UPLOAD, img_name) #设置图片保存的路径,settings.IMG_UPLOAD为settings.py中的属性,该属性需要自行设置
print(img_path)
#url = "..\static\picture\\" + img_name
with open(img_path, 'ab') as fp:
for chunk in f.chunks():
fp.write(chunk)
fp.close()
return HttpResponse("OK!")
else:
return HttpResponse("NOT OK!")
其中的settings.IMG_UPLOAD代码段,本人的路径是这个,其中BASE_DIR是项目的路径(setting.py中会自带有),'static/picture’为项目下面的文件夹(可根据自身要求设置),前提是static先要设置成静态路径。
IMG_UPLOAD=os.path.join(BASE_DIR,'static/picture')