# ***********文件上传************* def fileupload(request): if request.method=='GET': return render(request,'fileupload.html') if request.method=='POST': # FILES print(request.FILES) print(type(request.FILES.get('myfile'))) # 从字典里根据名字,把文件取出来 myfile=request.FILES.get('myfile') from django.core.files.uploadedfile import InMemoryUploadedFile # 文件名字 name=myfile.name # 打开文件,把上传过来的文件存到本地 with open(name,'wb') as f: # for line in myfile.chunks(): for line in myfile: f.write(line) return HttpResponse('ok')
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post" enctype="multipart/form-data"> {#<form action="" method="post" enctype="application/x-www-form-urlencoded">#} <input type="file" name="myfile"> <input type="text" name="password"> <input type="submit" value="提交"> </form> </body> </html>
ajax上传文件
1 def files_ajax(request): 2 # 提交文件从,request.FILES中取,提交的数据,从request.POST中取 3 name=request.POST.get('name') 4 print(name) 5 dic_files = request.FILES 6 myfile = dic_files.get('myfile') 7 with open(myfile.name, 'wb') as f: 8 # 循环上传过来的文件 9 for line in myfile: 10 # 往空文件中写 11 f.write(line) 12 return HttpResponse('ok')
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <script src="/static/jquery-3.3.1.js"></script> 6 <title>Title</title> 7 </head> 8 <body> 9 <form action="/files/" method="post" enctype="multipart/form-data"> 10 <p>用户名:<input type="text" name="name" id="name"></p> 11 12 <p><input type="file" name="myfile" id="myfile"></p> 13 14 <input type="submit" value="提交"> 15 16 </form> 17 <button id="btn">ajax提交文件</button> 18 19 </body> 20 <script> 21 $("#btn").click(function () { 22 //上传文件,必须用FormData 23 var formdata=new FormData(); 24 formdata.append('name',$("#name").val()); 25 //取出文件$("#myfile")[0].files拿到的是文件列表,取第0个把具体的文件取出来 26 formdata.append('myfile',$("#myfile")[0].files[0]); 27 28 $.ajax({ 29 url:'/files_ajax/', 30 type:'post', 31 //不预处理数据,(name=xqd&age=18) 32 processData:false, 33 //指定往后台传数据的编码格式(urlencoded,formdata,json) 34 //现在用formdata对象处理了,就不需要指定编码格式了,不要给我编码了 35 contentType:false, 36 data:formdata, 37 success:function (data) { 38 alert(data) 39 40 } 41 }) 42 43 }) 44 45 </script> 46 </html>