form表单上传文件:
//视图函数///def upload(request): ???if request.method=="POST": ???????print("POST", request.POST) ???????print("FILES",request.FILES) ?# FILES <MultiValueDict: {}> ???????file_obj=request.FILES.get("avatar") ???????print(file_obj.name,"-----") ???????with open(file_obj.name,"wb") as f: ???????????for i in file_obj: ???????????????f.write(i) ???????return HttpResponse("成功") ???return render(request,"upload.html")////模板文件/////<h3>form表单上传文件</h3><form action="/upload_file/" method="post" enctype="multipart/form-data"> ???<p><input type="file" name="upload_file_form"></p> ???<input type="submit"></form>
使用Ajax(FormData)上传文件:
<!DOCTYPE html><html lang="en"><head> ???<meta charset="UTF-8"> ???<meta http-equiv="X-UA-Compatible" content="IE=edge"> ???<meta name="viewport" content="width=device-width, initial-scale=1"> ???<title>Title</title> ???<style> ???????.login_error{ ???????????color: red; ???????} ???</style></head><body>{% csrf_token %}<form action="" id="s1"> ???<p>姓名<input type="text"></p> ???<p>密码<input type="password"></p> ???<p>头像<input type="file" id="upload_avatar"></p></form><p><button class="Ajax_send">Ajax_send</button><span class="login_error"></span></p><script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js "></script>{#<script src="/static/index.js"></script>#}<script src="https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.js"></script><script> ????function foo() { ???????$(".login_error").html("") ???} ???$(".Ajax_send").click(function () { ???????var formData=new FormData(); ???????formData.append("username",$(":text").val()); ???????formData.append("password",$(":password").val()); ???????formData.append("avatar",$("#upload_avatar")[0].files[0]); ???????// ajax请求 ???????$.ajax({ ???????????url:"/get_ajax/", ???????????type:"POST", ???????????headers:{"X-CSRFToken":$.cookie(‘csrftoken‘)}, ???????????data:formData, ???????????contentType:false, ???????????processData:false, ???????????success:function (data) { ???????????????var data=JSON.parse(data); ???????????????console.log(data); ???????????????console.log(typeof data); ???????????????// $(".error").html(data) ???????????????if(!data["flag"]){ ???????????????????$(".login_error").html("用户名或者密码错误") ???????????????????setTimeout(foo,3000) ???????????????} ???????????} ???????}) ???})</script></body></html>
上传文件
原文地址:http://www.cnblogs.com/ldq1996/p/7834471.html