Django實現(xiàn)文件上傳和下載功能
本文實例為大家分享了Django下完成文件上傳和下載功能的具體代碼,供大家參考,具體內(nèi)容如下
一、文件上傳
Views.py
def upload(request): if request.method == "POST": # 請求方法為POST時,進(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
<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會直接使用迭代器對象,將迭代器對象的內(nèi)容存儲城字符串,然后返回給客戶端,同時釋放內(nèi)存??梢援?dāng)文件變大看出這是一個非常耗費(fèi)時間和內(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.
這是一種非常省時省內(nèi)存的方法。但是因為StreamingHttpResponse的文件傳輸過程持續(xù)在整個response的過程中,所以這有可能會降低服務(wù)器的性能。
urls.py
url(r'^upload',views.upload),
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python使用openpyxl庫讀取Excel文件數(shù)據(jù)
openpyxl是一個功能強(qiáng)大的庫,可以輕松地實現(xiàn)Excel文件的讀寫操作,本文將介紹如何使用openpyxl庫讀取Excel文件中的數(shù)據(jù),感興趣的小伙伴可以了解下2023-11-11Python庫urllib與urllib2主要區(qū)別分析
這篇文章主要介紹了Python庫urllib與urllib2主要區(qū)別,需要的朋友可以參考下2014-07-07