這篇文章將為大家詳細(xì)講解有關(guān)使用Django怎么實(shí)現(xiàn)文件上傳和下載功能,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。
一、文件上傳
Views.py
def upload(request): if request.method == "POST": # 請(qǐng)求方法為POST時(shí),進(jìn)行處理 myFile = request.FILES.get("myfile", None) # 獲取上傳的文件,如果沒有文件,則默認(rèn)為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+') # 打開特定的文件進(jìn)行二進(jìn)制的寫操作 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
頁(yè)面顯示
二、文件下載
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會(huì)直接使用迭代器對(duì)象,將迭代器對(duì)象的內(nèi)容存儲(chǔ)城字符串,然后返回給客戶端,同時(shí)釋放內(nèi)存??梢援?dāng)文件變大看出這是一個(gè)非常耗費(fèi)時(shí)間和內(nèi)存的過程。
而StreamingHttpResponse是將文件內(nèi)容進(jìn)行流式傳輸,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.
這是一種非常省時(shí)省內(nèi)存的方法。但是因?yàn)镾treamingHttpResponse的文件傳輸過程持續(xù)在整個(gè)response的過程中,所以這有可能會(huì)降低服務(wù)器的性能。
urls.py
url(r'^upload',views.upload),
關(guān)于使用Django怎么實(shí)現(xiàn)文件上傳和下載功能就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。