最近一個用django開發的web項目要進行數據的導入導出,所以有必要了解下。
django中主要用HttpResponse將請求結果返回給瀏覽器,所以文件的下載也是通過改對象進行處理的,具體的一個列子的代碼如下:
最近一個用django開發的web項目要進行數據的導入導出,所以有必要了解下。 django中主要用HttpResponse將請求結果返回給瀏覽器,所以文件的下載也是通過改對象進行處理的,具體的一個列子的代碼如下: [python] view plain copy #文件下載 def download(request): """ Send a file through Django without loading the whole file into memory at once. The FileWrapper will turn the file object into an iterator for chunks of 8KB. """ #讀取mongodb的文件到臨時文件中 fileid_=request.GET["fileid"] filepath_ = ('%s/%s'%(MEDIA_ROOT, fileid_)) #文件全路徑 file_=TFiles.objects.get(fileid=int(fileid_)) filename_=file_.filename filetype_=file_.filetype if os.path.isfile(filepath_): pass else: mongoLoad(fileid_) #下載文件 def readFile(fn, buf_size=262144):#大文件下載,設定緩存大小 f = open(fn, "rb") while True:#循環讀取 c = f.read(buf_size) if c: yield c else: break f.close() response = HttpResponse(readFile(filepath_), content_type='APPLICATION/OCTET-STREAM') #設定文件頭,這種設定可以讓任意文件都能正確下載,而且已知文本文件不是本地打開 response['Content-Disposition'] = 'attachment; filename='+filename_.encode('utf-8') + filetype_.encode('utf-8')#設定傳輸給客戶端的文件名稱 response['Content-Length'] = os.path.getsize(filepath_)#傳輸給客戶端的文件大小 return response