萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Django 實作點擊圖片連結強制下載(大檔案支援)

預設瀏覽器會直接開啟圖片連結,若需強制下載,可在 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 編碼處理中文檔名。

適用場景: 大檔案下載、私有檔案存取控制、動態產生檔案(如報表匯出)。

copyright © 萬盛學電腦網 all rights reserved