預設瀏覽器會直接開啟圖片連結,若需強制下載,可在 Django 視圖中設定 Content-Disposition: attachment 標頭。本文提供使用生成器分塊讀取的大檔案下載視圖範例,避免一次讀入記憶體造成 OOM。
def Download(request):
def readFile(fn, buf_size=262144):
with open(fn, "rb") as f:
while True:
c = f.read(buf_size)
if c:
yield c
else:
break
filename = '/usr/local/1.jpg'
try:
response = HttpResponse(readFile(filename), mimetype='application/octet-stream')
response['Content-Disposition'] = 'attachment; filename="%s"' % 'attachment'
except:
response = HttpResponse('')
return response
readFile 生成器:每次讀取 256KB,配合 HttpResponse 串流輸出。mimetype='application/octet-stream':告知瀏覽器為二進位檔案。Content-Disposition: attachment:強制觸發下載對話框。filename 參數:建議使用 URL 編碼處理中文檔名。適用場景: 大檔案下載、私有檔案存取控制、動態產生檔案(如報表匯出)。