Django之上传文件
Django之上传文件
最简单的文件上传方式:
后端代码:
def f1(request): if request.method == "GET": return render(request,"f1.html") else: import os print(request.FILES) #这里是文件的数据 request.POST 是取文本的数据 file_obj = request.FILES.get("fafafa") #获取用户上传的文件 print(file_obj.name) #文件名 print(file_obj.size) #文件大小 f = open(os.path.join("static",file_obj.name),"wb") for chunk in file_obj.chunks(): f.write(chunk) f.close() return render(request,"f1.html")
前端代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="post" action="/f1/" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="fafafa"> <input type="submit" value="提交"> </form> </body> </html>
基于Form验证的文件操作:
后端操作:
class F2Form(Form): user = fields.CharField() fafafa = fields.FileField() def f2(request): """ 文件上传 :param request: :return: """ if request.method == "GET": obj = F2Form() return render(request,"f2.html",{"obj":obj}) else: obj = F2Form(data=request.POST,files=request.FILES) if obj.is_valid(): print(obj.cleaned_data.get("fafafa").name) #拿文件名 print(obj.cleaned_data.get("fafafa").size) #拿文件大小 return render(request,"f2.html",{"obj":obj})
前端代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="post" action="/f2/" enctype="multipart/form-data"> {% csrf_token %} {{ obj.user }} {{ obj.fafafa }} <input type="submit" value="提交"> </form> </body> </html>
Ajax 的上传文件:
1.XMLHttpResponse方式:
后端:
import os def upload(request): if request.method == "GET": return render(request,'upload.html') else: print(request.POST,request.FILES) file_obj = request.FILES.get('fafafa') file_path = os.path.join("static",file_obj.name) with open(file_path,'wb') as f: for chunk in file_obj.chunks(): f.write(chunk) return HttpResponse(file_path)
前端:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <h1>原生Ajax上传文件</h1> <input type="file" id="i1" /> <a onclick="upload1();">上传</a> <div id="container1"></div> //存放路径 <script src="/static/jquery-1.12.4.js"></script> <script> function upload1(){ var formData = new FormData(); //FormData能传文件,能传字符串 formData.append('k1','v1'); formData.append('fafafa',document.getElementById('i1').files[0]); var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ var file_path = xhr.responseText; var tag = document.createElement('img'); tag.src = "/"+ file_path; document.getElementById('container1').appendChild(tag); //存放路径 } }; xhr.open('POST','/upload/'); xhr.send(formData); } </script> </body> </html>
2.jQuery Ajax方式:
前端:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <h1>jQuery Ajax上传文件</h1> <input type="file" id="i2" /> <a onclick="upload2();">上传</a> <div id="container2"></div> //存放路径 <script src="/static/jquery-1.12.4.js"></script> <script> function upload2(){ var formData = new FormData(); formData.append('k1','v1'); // formData.append('fafafa',document.getElementById('i1').files[0]); formData.append('fafafa',$('#i2')[0].files[0]); // $('#i2') -> $('#i2')[0] // document.getElementById('i1') -> $(document.getElementById('i1')) $.ajax({ url: '/upload/', type: 'POST', data: formData, contentType:false, processData:false, success:function(arg){ var tag = document.createElement('img'); tag.src = "/"+ arg; $('#container2').append(tag); } }) } </script> </body> </html>
3.伪Ajax方式:
前端:伪Ajax上传解决了浏览器低版本问题,应用了iframe提交form表单不刷新页面的特点。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <h1>伪 Ajax上传文件</h1> <form id="f1" method="POST" action="/upload/" target="ifr" enctype="multipart/form-data"> <iframe id="ifr" name="ifr" style="display: none"></iframe> <input type="file" name="fafafa" /> <a onclick="upload3();">上传</a> </form> <div id="container3"></div> <script src="/static/jquery-1.12.4.js"></script> <script> function upload3(){ document.getElementById('ifr').onload = loadIframe; document.getElementById('f1').submit(); } function loadIframe(){ var content = document.getElementById('ifr').contentWindow.document.body.innerText; var tag = document.createElement('img'); tag.src = "/"+ content; $('#container3').append(tag); } </script> </body> </html>
----- END ------