問題描述: 已知一個下載鏈接 download_url,直接下載下來的話,文件名是 xxx.xlsx, 根據產品要求,文件名必須是filename.xlsx.
解決問題:
方案1: 前端js去修改, 網上看了下, <a href="http://somehost/somefile.zip" download="filename.zip">Download file</a>
在html標簽<a>加上download屬性,但是好像並沒有什么用,具體可以查看原文地址:
https://scarletsky.github.io/2016/07/03/download-file-using-javascript/
方案2: 后台先去下載保存在服務器,然后再下載給前端頁面, 這樣是可以,但是比較方案比較垃圾,下載時間翻倍,這里不做介紹
方案3: 使用python flask框架的stream流,相當於一個管道一樣,將第三方地址的下載流轉換到當前頁面,下面是代碼的實現
import requests
from flask import request, stream_with_context, Response
def file_downlad(url, file_name):
# 首先定義一個生成器,每次讀取512個字節
def generate():
r = requests.get(url, cookies=request.cookies, stream=True)
for chunk in r.iter_content(chunk_size=512):
if chunk:
yield chunk
response = Response(stream_with_context(generate()))
content_disposition = "attachment; filename={}".format(file_name)
response.headers['Content-Disposition'] = content_disposition
return response
ps: 代碼存手寫,格式不對,拼寫錯誤難免會發生