实现原理:定义的接口不是下载文件的路径,而是通过API可以获得文件的内容,由前端把内容写入到文件中,这种方法是通过获取文件信息,在网页上利用click事件,创建一个文件,然后将文件信息写入到文件中,然后保存。
主要用到了JavaScript中的Blob对象和HTML5中的FileReader对象。代码如下:
python/django:
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import csv
from django.http import StreamingHttpResponse
#下载
@csrf_exempt
def download(request):
# Create the HttpResponse object with the appropriate CSV header.
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
writer = csv.writer(response)
writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])
return response
js:
<script src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.min.js"></script>
axios.post('/article/download/', {}, {
responseType: 'blob'
}).then((res) => {
console.log('res', res);
const blob = res.data;
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = (e) => {
const a = document.createElement('a');
a.download = `csv.csv`;
// 后端设置的文件名称在res.headers的 "content-disposition": "form-data; name=\"attachment\"; filename=\"20181211191944.zip\"",
a.href = e.target.result;
console.log(e.target.result);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
};
}).catch((err) => {
console.log(err.message);
});
FileReader:https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader
https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL#Live_Result
Blob:https://developer.mozilla.org/zh-CN/docs/Web/API/Blob