Js word格式doc文件下载

一、 下载方式

a) 获取后端传过来的url 静态资源

  • 通过a标签做点击操作

  • Window.location.href = url下载

  • Window.open(url)下载

b) 文件流下载(application/json; application/octet-stream)

  • 文件流获取转换blob对象模拟a标签点击下载

二、 下载doc文件流示例

a) 后端主要代码
在这里插入图片描述

b) 前端主要代码

  • Axios Api请求如下:
export const reportDownload = row => {
  return request({
    url:  '/api/diagnose/download/'+ row.id + '/' + row.filetype ,
    method: 'get',
    responseType: "blob",
    headers: {
      'Content-Type': 'application/json; application/octet-stream'
    },
    data: row
  })
};
  • response数据如下:
    在这里插入图片描述

  • 获取数据并模拟a标签点击:

const blob = new Blob([res.request.response], {type: 'application/msword'});
const fileName = decodeURI(res.headers['content-disposition'].split('=')[1]) +".doc";
if ("download" in document.createElement("a")) {
	// 非IE下载
	const elink = document.createElement("a");
	elink.download = fileName;
	elink.style.display = "none";
	elink.href = URL.createObjectURL(blob);
	document.body.appendChild(elink);
	elink.click();
	URL.revokeObjectURL(elink.href); // 释放URL 对象
	document.body.removeChild(elink);
} else {
	// IE10+下载
	navigator.msSaveBlob(blob, fileName);
} 

三、 文件流下载关键点说明

a) 后端

  • 设置字符集和文件后缀名
response.setContentType("application/msword;" + "charset = UTF-8"); 
  • 设置文件名称,这里encode必须设置,前端decodeURI解析,否则中文乱码
response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(diagnoseReport.getName(), "UTF-8"));
  • 设置response字符集
response.setCharacterEncoding("UTF-8");

b) 前端

  • Ajax请求api中的response类型必须添加(因为response回传不存在blob类型,默认字符串,会导致下载的文件无法解析)
responseType: "blob"
  • blob获取需要标注文件类型
new Blob([res.request.response], {type: 'application/msword'});
  • 获取文件名字,用decodeURI解码
decodeURI(res.headers['content-disposition'].split('=')[1]) +".doc";
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Mr.T's Blog

感谢打赏

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

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

打赏作者

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

抵扣说明:

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

余额充值