<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="/static/jquery-1.12.4.js"></script>
</head>
<body>
<form method="POST" action="/upload/" enctype="multipart/form-data">
<input type="text" name="user" id="user"><br>
<input type="file" name="image" id="img"><br>
<input type="submit" value="提交">
</form>
<a οnclick="UploadFile();" style="color: red;cursor:pointer;">XMLRequest按钮上传</a>
<a οnclick="UploadFile2();" style="color: red;cursor:pointer;">XMLRequest按钮上传</a>
</body>
<script>
function UploadFile()
{
var formDa=new FormData();
formDa.append("user",document.getElementById("user").value);
var file=document.getElementById("img").files[0];
formDa.append("img",file);
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function()
{
var data=xhr.responseText;
console.log(data);
};
xhr.open("post","/upload/",true);
xhr.send(formDa);
}
function UploadFile2(){
var formD=new FormData();
formD.append("user",$("#user").val());
var fileobj=$("#img")[0].files[0];
formD.append("imgg",fileobj);
$.ajax({
url:"/upload/",
type:"POST",
data:formD,
processData:false,
contentType:false,
success: function (data) {
console.log(data);
}
})
}
</script>
</html>
后台代码:
def upload(request):
if request.method=="POST":
user=request.POST.get("user",None)
img=request.FILES.get("imgg",None)
from django.core.files.uploadedfile import TemporaryUploadedFile
print(img._get_name(),type(img))
f=open(os.path.join("statics",img.name),"wb")
for chunck in img.chunks():
f.write(chunck)
f.close()
return HttpResponse("ok")
return render(request,"upload.html")
Django利用Ajax提交文件到后台
原创wx5e6caa8b9792d 博主文章分类:Python自动化开发 ©著作权
©著作权归作者所有:来自51CTO博客作者wx5e6caa8b9792d的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章