项目背景

下载文件到本地

<button @click="downLoad">导出</button>

 代码实现

1. 调用接口,将后端返回的流数据new一个文件对象

    使用限制:文件过大浏览器会连接中断,导致文件损坏,大约200KB


exportFile (method, data) {
	Vue.prototype.$axios[method]("http:// xxxxxx.com", {
		data: data
	},
	// 必须设置类型
	{responseType: 'arraybuffer'}).then(res => {
	    
			let blob = new Blob([res], { type: 'application/x-xls' });
			var filename = "download.xls";
			var a = document.createElement('a');
			var url = window.URL.createObjectURL(blob);
			a.href = url;
			a.download = filename;
			var body = document.getElementsByTagName('body')[0];
			body.appendChild(a);
			a.click();
			body.removeChild(a);
			window.URL.revokeObjectURL(url);
		
	})
}

2. 推荐解决方式,使用get请求地址拼接参数

 handleDownload(item) {
      let elemIF = document.createElement("iframe");
      elemIF.src = `${this.downloadURL}name=${encodeURIComponent(
        encodeURIComponent(item.name)
      )}&path=${item.path}&secret=${this.md5Res(item.name)}`;
      elemIF.style.display = "none";
      document.body.appendChild(elemIF);
    },

  温馨提示:当文件名称中有? & = 特殊字符,需要用encodeURIComponent进行转义

Logo

前往低代码交流专区

更多推荐