from django.utils.encoding import escape_uri_path
from django.shortcuts import HttpResponse
def file_download(request):
file_name = "凸凸.jpg"
res = requests.get("https://nihaoshijie-17600663122-1588242519000-1301483025.cos.ap-beijing.myqcloud.com/%E5%87%B8%E5%87%B8.jpg")
# 文件分塊處理
data = res.iter_content()
# 設置內容類型 content_type=application/octet-stream (二進制流數據) 提示下載框
response = HttpResponse(data, content_type="application/octet-stream")
# 設置響應頭:escape_uri_path中文件文件名轉義
response['Content-Disposition'] = f"attachment; filename={escape_uri_path(file_name)};"
'''
Content-Disposition可以控制用戶請求所得的內容存為一個文件的時候提供一個默認的文件名,文件直接在瀏覽器上顯示或者在訪問時彈出文件下載對話框。
如attachment為以附件方式下載,會直接在瀏覽器中顯示,如果需要提示用戶保存,就要利用Content-Disposition進行一下處理,關鍵在於一定要加上attachment
'''
return response