1. 程式人生 > 程式設計 >Django實現檔案上傳和下載功能

Django實現檔案上傳和下載功能

本文例項為大家分享了Django下完成檔案上傳和下載功能的具體程式碼,供大家參考,具體內容如下

一、檔案上傳

Views.py

def upload(request):
  if request.method == "POST": # 請求方法為POST時,進行處理
    myFile = request.FILES.get("myfile",None) # 獲取上傳的檔案,如果沒有檔案,則預設為None
    if not myFile:
      return HttpResponse("no files for upload!")
    # destination=open(os.path.join('upload',myFile.name),'wb+')
    destination = open(
      os.path.join("你的檔案存放地址",'wb+') # 開啟特定的檔案進行二進位制的寫操作
    for chunk in myFile.chunks(): # 分塊寫入檔案
      destination.write(chunk)
    destination.close()
    return HttpResponse("upload over!")
  else:
    file_list = []
    files = os.listdir('D:\python\Salary management system\django\managementsystem\\file')
    for i in files:
      file_list.append(i)
    return render(request,'upload.html',{'file_list': file_list})

urls.py

url(r'download/$',views.download),

upload.html

<div class="container-fluid">
  <div class="row">
    <form enctype="multipart/form-data" action="/upload_file/" method="POST">
      <input type="file" name="myfile"/>
      <br/>
      <input type="submit" value="upload"/>
    </form>
  </div>
</div>

頁面顯示

二、檔案下載

Views.py

from django.http import HttpResponse,StreamingHttpResponse
from django.conf import settings
 
def download(request):
  filename = request.GET.get('file')
  filepath = os.path.join(settings.MEDIA_ROOT,filename)
  fp = open(filepath,'rb')
  response = StreamingHttpResponse(fp)
  # response = FileResponse(fp)
  response['Content-Type'] = 'application/octet-stream'
  response['Content-Disposition'] = 'attachment;filename="%s"' % filename
  return response
  fp.close()

HttpResponse會直接使用迭代器物件,將迭代器物件的內容儲存城字串,然後返回給客戶端,同時釋放記憶體。可以當檔案變大看出這是一個非常耗費時間和記憶體的過程。

而StreamingHttpResponse是將檔案內容進行流式傳輸,StreamingHttpResponse在官方文件的解釋是:

The StreamingHttpResponse class is used to stream a response from Django to the browser. You might want to do this if generating the response takes too long or uses too much memory.

這是一種非常省時省記憶體的方法。但是因為StreamingHttpResponse的檔案傳輸過程持續在整個response的過程中,所以這有可能會降低伺服器的效能。

urls.py

url(r'^upload',views.upload),

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。