vue下载excel模板

一、错误示例
1、请求接口

export const downloadTemplateApi = () => {
  return request({
    url: '/file/downloadTemplate',
    method: 'get'
  })
}

2、请求代码

	async downloadFnA () {
	  const res = await downloadTemplateApi({responseType: 'blob'}) 
	  const blob = new Blob([res], {type: 'application/vnd.ms-excel;charset=utf-8'})
	  const fileName = '空白导入模版'
	  if ('download' in document.createElement('a')) {
	    const link = document.createElement('a')
	    link.href = window.URL.createObjectURL(blob)
	    link.download = fileName
	    link.click()
	    window.URL.revokeObjectURL(blob)
	  } else {
	    window.navigator.msSaveBlob(blob, fileName)
	  }
	},

3、请求回来的文件流数据 (就是请求代码中的res)
vue下载excel模板_第1张图片
4、下载结果
vue下载excel模板_第2张图片
二、成功案例

1、下载按钮

<el-link type="warning" @click.stop="downloadFnA">下载空白模板</el-link>

2、方法

async downloadFnA () {	
 	 const res = await downloadGoodsbaseTemplateApi({responseType: 'blob'}) 
 	 // 非IE浏览器
     if ('download' in document.createElement('a')) {   
        const link = document.createElement('a');
			link.style.display="none";
		let binaryData = [];
			binaryData.push(res);
			link.href = window.URL.createObjectURL(new Blob(binaryData));
			link.setAttribute("download", "导入模版.xlsx");
			document.body.appendChild(link);
			link.click();
			document.body.removeChild(link);
      } else {
      //IE浏览器
        window.navigator.msSaveBlob(new Blob(binaryData), fileName)
      }
    },

3、downloadGoodsbaseTemplateApi请求接口

export const downloadGoodsbaseTemplateApi = () => {
  return request({
    url: '/file/downloadGoodsbaseTemplate',
    method: 'get',
	responseType:"arraybuffer"   
  })
}

注:必须要添加responseType:“arraybuffer”
4、下载结果
vue下载excel模板_第3张图片
参考文章:https://blog.csdn.net/WuqibuHuan/article/details/125442079

你可能感兴趣的:(vue,vue.js,前端,javascript)