django 檔案上傳下載
阿新 • • 發佈:2019-01-06
views:
def mgmt_files(request): #列出樹形目錄,上傳檔案頁面 if request.method == 'POST': path_root = "D:\\py\\ITFiles" #上傳檔案的主目錄 myFile =request.FILES.get("file", None) # 獲取上傳的檔案,如果沒有檔案,則預設為None if not myFile: dstatus = "請選擇需要上傳的檔案!" else: path_ostype= os.path.join(path_root,request.POST.get("ostype")) path_dst_file = os.path.join(path_ostype,myFile.name) # print path_dst_file if os.path.isfile(path_dst_file): dstatus = "%s 已存在!"%(myFile.name) else: destination = open(path_dst_file,'wb+') # 開啟特定的檔案進行二進位制的寫操作 for chunk in myFile.chunks(): # 分塊寫入檔案 destination.write(chunk) destination.close() dstatus = "%s 上傳成功!"%(myFile.name) return HttpResponse(str(dstatus)) return render(request,'sinfors/mgmt_files.html') def mgmt_file_download(request,*args,**kwargs): #提供檔案下載頁面 #定義檔案分塊下載函式 def file_iterator(file_name, chunk_size=512): with open(file_name,'rb') as f: #如果不加‘rb’以二進位制方式開啟,檔案流中遇到特殊字元會終止下載,下載下來的檔案不完整 while True: c = f.read(chunk_size) if c: yield c else: break path_root = "D:\\py\\ITFiles" if kwargs['fpath'] is not None and kwargs['fname'] is not None: file_fpath = os.path.join(path_root,kwargs['fpath']) #kwargs['fapth']是檔案的上一級目錄名稱 file_dstpath = os.path.join(file_fpath,kwargs['fname']) #kwargs['fname']是檔名稱 response = StreamingHttpResponse(file_iterator(file_dstpath)) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename="{0}"'.format(kwargs['fname']) #此處kwargs['fname']是要下載的檔案的檔名稱 return response
StreamingHttpResponse物件用於將檔案流傳送給瀏覽器,與HttpResponse物件非常相似,對於檔案下載功能,使用StreamingHttpResponse物件更合理。通過檔案流傳輸到瀏覽器,但檔案流通常會以亂碼形式顯示到瀏覽器中,而非下載到硬碟上,因此,還要在做點優化,讓檔案流寫入硬碟,給StreamingHttpResponse物件的Content-Type和Content-Disposition欄位賦下面的值即可,如:
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="filename.txt"'
html頁面:
<form id="uploadForm" enctype="multipart/form-data"> //檔案上傳的form {% csrf_token %} <input id="file" type="file" name="file" > //上傳檔案 <input type="radio" name="ostype" value="Windows" />Windows <input type="radio" name="ostype" value="Linux" />Linux <input type="radio" name="ostype" value="Network" />Network <input type="radio" name="ostype" value="DB" />DB <button id="upload" type="button" style="margin:20px">上傳</button> </form>
js頁面:
$("#upload").click(function(){ // alert(new FormData($('#uploadForm')[0])); var ostype = $('input:radio:checked').val() if (ostype == undefined){ alert('請選擇上傳的檔案型別'); } //獲取單選按鈕的值 $.ajax({ type: 'POST', // data:$('#uploadForm').serialize(), data:new FormData($('#uploadForm')[0]), processData : false, contentType : false, //必須false才會自動加上正確的Content-Type // cache: false, success:function(response,stutas,xhr){ // parent.location.reload(); //window.location.reload(); // alert(stutas); alert(response); }, // error:function(xhr,errorText,errorStatus){ // alert(xhr.status+' error: '+xhr.statusText); // } timeout:6000 }); });