java流下载,前端ajax blob接收

不多说,直接干代码。

java后端代码:

@PostMapping(value = "/download")
public void download(String name, HttpServletResponse response) throws Exception {
    InputStream is = DemoController.class.getClassLoader().getResourceAsStream("node/" + name);
	ByteArrayOutputStream bos = new ByteArrayOutputStream();
	int b = 0;
	byte[] buffer = new byte[512];
	while (b != -1) {
		b = is.read(buffer);
		if (b != -1) {
			bos.write(buffer, 0, b);// 4.写到输出流(out)中
		}
	}
	String fileName = name.contains("/") ? name.substring(name.lastIndexOf("/") + 1) : name;
	response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
	response.addHeader("Content-Length", "" + (buffer.length));
	response.setHeader("filename", fileName);
	response.setContentType("application/octet-stream");
	ServletOutputStream out = response.getOutputStream();
	out.write(bos.toByteArray());
	out.flush();
	out.close();
}

几个注意点:

1.用@controller 不要用 @RestContoller,

2.out.write一定要放在setHeader后面,不然response头不会生效。

------------------------------------------华丽分割线--------------------------------------------------

js前端代码

success : function(data) {
    const blob = new Blob([data]);
    const a = document.createElement("a");
    const url = window.URL.createObjectURL(blob);
    const filename = name;
    a.href = url;
    a.target = "_blank";
    a.download = filename;// 从response header里面取
    a.click();
    window.URL.revokeObjectURL(url);
}

几个注意点:

1.xhr(ajax的请求对象,不知道就看书去吧) xhr.responseType = "blob"

2.success 中返回的data对象是 xhr.response

3.success函数最好别用lambda,this指针指向xhr对象,可以获取responseHeader信息

高手忘记的API的直接copy代码走人,新手看不懂的直接扣代码走人,想提高学习的,看下注意信息,so so

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值