Django+Vue实现各样式文件下载

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

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 <
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱学习的狮王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值