Django:
# 这里返回一个迭代器,防止文件过大将内存打满,这样可以保证服务的占用内存几乎没有波动
def read_file(file_name, buf_size=409600):
with open(file_name, "rb") as f:
while True:
c = f.read(buf_size)
if c:
yield c
else:
break
@action(detail=False, methods=['POST'])
def export_templates(self, request, *args, **kwargs):
file_name = "取的名字根据项目上下文决定"
# 使用文件流的方式返回
res = StreamingHttpResponse(read_file(file_name))
# 增加headers
res['Content-Type'] = 'application/octet-stream'
res['Access-Control-Expose-Headers'] = "Content-Disposition, Content-Type"
res['Content-Disposition'] = "attachment;"
return res
Vue:
这里对axios的封装就不说了
axios请求的参数: url,方法名,参数,responseType要带上:
url: ‘xxxx’,
method: ‘post’,
responseType: ‘blob’,
data
请求后返回的response处理:
.then(response => {
const filename = "xxx" + '.tar'
const blob = new Blob([response], {
type: 'application/x-tar'
})
// console.log("fileName",fileName)
if <

该博客介绍了如何在Django中通过StreamingHttpResponse实现大文件下载,以防止内存溢出,并在Vue端利用axios进行响应类型设置为blob的请求,然后解析并保存文件。内容涵盖了不同文件类型的MIME类型,以及在不同浏览器环境下使用Blob对象保存文件的方法。
最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



