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("你的文件存放地址", myFile.name),
      '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),

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章