VUE专题 elementUI+VUE 使用Blob提供JS文件下载

前端

这里的el-button 是在el-table中的table列中

<Button type="text" size="small" @click="downloadFile(scope.$index,scope.row)">下载</Button>
downloadFile (index, row) {
downLoad({fileName:row.fileAllName,filePath:row.filePath}).then(res => {
this.download(res, row)
}).catch(err => {
this.$message.error('下载失败:' + err)
})
},
download (data, row) {
if (!data) {
return
}
let url = window.URL.createObjectURL(new Blob([data]))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
// 获取文件名
// download 属性定义了下载链接的地址而不是跳转路径
link.setAttribute('download', row.fileName)
document.body.appendChild(link)
link.click()
},

前端请求API

export function downLoad (data) {
	return request({
	url: '/file/download',
	method: 'post',
	responseType: 'blob',
	data
	})
}

后台请求

@PostMapping("/download")
	public void doenloadFile(@RequestBody Map<String,Object> map ,HttpServletResponse response) throws Exception {

		String fileName= (String) map.get("fileName");
		String filePath= (String) map.get("filePath");

		File file = new File(filePath+"/"+fileName);
		
		if(file.exists()) {
			FileInputStream input=null;
			byte[] data = null;
			
			try {
				input = new FileInputStream(file);
				data = new byte[input.available()];
				
				input.read(data);
				
				response.setContentType("application/x-download;charset=UTF-8");
				response.setHeader("Content-Disposition", "attachment;filename*=UTF-8"+URLEncoder.encode(fileName,"UTF-8"));
				response.getOutputStream().write(data);

			} catch (Exception e) {
				logger.error("下载失败,原因如下:", e);
			}finally {
				input.close();
			}

		}else {
			// 未找到文件
		}
	}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值