前端代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/static/jquery-3.2.1.min.js"></script>
<script src="/static/jquery.cookie.js"></script>
</head>
<body>
<h1>文件上传页面</h1>
<form action="/upload/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>用户名:<input type="text" name="username"></p>
<p>文件:<input type="file" name="file"></p>
<input type="submit" value="提交"><span>{{ successful }}</span>
</form>
</body>
</html>
后端处理:
def upload(request):
if request.method == "GET":
return render(request,"upload.html")
else:
file_obj = request.FILES.get("file")
with open(file_obj.name,"wb") as f:
for line in file_obj:
f.write(line)
successful = "上传成功"
return render(request,"upload.html",locals())
效果图:
利用formdata上传文件:
用formdata上传需要先建立一个对象,然后这个对象吧里面的值append进去,串数据的时候直接把formdate串过去就好了
前端代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="/static/jquery-3.2.1.min.js"></script> <script src="/static/jquery.cookie.js"></script> </head> <body> <form action="" id="s1"> <p>姓名:<input type="text"></p> <p>密码:<input type="password"></p> <p>头像:<input type="file" id="upload" name="file"></p> </form> <p><button class="Ajax_send">Ajax_send</button><span class="login_error"></span></p> #button需要放在form表单外边 </body> <script> function foo() { $(".login_error").html("") } $(".Ajax_send").click(function () { var formDate = new FormData(); formDate.append("username",$(":text").val()); formDate.append("password",$(":password").val()); formDate.append("avatar",$("#upload")[0].files[0]); $.ajax({ url:"/ajax_form/", type:"POST", headers:{"X-CSRFToken":$.cookie('csrftoken')}, data:formDate, contentType:false, processData:false, success:function (data) { var data = JSON.parse(data); if(!data["flag"]){ $(".login_error").html("用户名或密码错误") setTimeout(foo,3000) } else{ alert("上传成功") } } }) }) </script> </html>
后端代码:
def ajax_form(request):
if request.method == "GET":
return render(request,"formdate.html")
else:
username = request.POST.get("username")
password = request.POST.get("password")
file_obj = request.FILES.get("avatar")
print("===================>",file_obj)
with open(file_obj.name, "wb") as f:
for line in file_obj:
f.write(line)
response = {"flag":False}
if username=="username" and password == "password":
response["flag"] = True
import json
return HttpResponse(json.dumps(response))
简单的上传操作会让页面刷新,还有利用ajax无刷新技术上传的方式↓