<!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")