这里只列出关键部分
urls.py
urlpatterns = [
# 其他
path('file_put/', views.file_put),
]
views.py
def file_put(request):
if request.method == "POST":
#print("body-->", request.body)
print("POST-->", request.POST)
print(request.POST.get("user"))
print(request.FILES)
# dowload file code
file_obj = request.FILES.get("avatar")
with open(file_obj.name, "wb") as f:
for line in file_obj:
f.write(line)
return HttpResponse("OK")
return render(request, "upload.html")
upload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>基于Ajax的文件上传</h3>
<form action="" method="post" enctype="multipart/form-data">
用户名 <input type="text" id="user">
头像 <input type="file" id="avatar">
<input type="button" class="btn" value="Ajax">
</form>
<script src="/static/jquery-3.3.1.min.js"></script>
<script>
$(".btn").click(function () {
var formdata = new FormData();
formdata.append("user", $("#user").val());
formdata.append("avatar", $("#avatar")[0].files[0]);
$.ajax({
url:"/file_put/",
type:"post",
contentType:false,
processData:false,
data:formdata,
success:function (data) {
console.log(data);
}
});
});
</script>
</body>
</html>