springboot+vue+element-ui下载excel模板本代码基于Vue项⽬(此处暂不做深⼊,仅对⽂件流下载做⼀个记录)
1. HTML部分
<div><el-button @click="download">下载</el-button><div>
2. javascript部分
download() {
let _this = this;
let fileName = `单位客户导⼊模板_${new Date().getTime()}.xlsx`;
axios({
method: 'POST',
url: `/download/${new Date().getTime()}`,
data: {},
responseType: 'blob'
}).then(response => {
if (!response) {
return
}
_this.$message({
type:'info',
showClose:true,
duration:3000,
message:`已成功下载⽂件!${fileName}`
});
const blob = new Blob([response.data])
debugger;
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, fileName)
} else {
let u = ateObjectURL(response.data)
let aLink = ateElement('a')
aLink.style.display = 'none'
aLink.href = u
aLink.setAttribute('download', fileName)
document.body.appendChild(aLink)
aLink.click()
veChild(aLink)
vokeObjectURL(u)
}
}).catch(error=> {
_this.$message({
type:'error',
前端页面模板showClose:true,
duration:3000,
message:'请求失败! error:'+error
});
});
}
3. 后台Java代码
import io.ClassPathResource;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
/**
* 单位客户Excel⽂件模板下载
* 获取模板⽂件的字节流,返回到前端页⾯,前端页⾯对字节流进⾏封装处理并执⾏下载操作
* @param time 时间戳
* @return blob
* @throws IOException
*/
@RequestMapping(value="/download/{time}",method={RequestMethod.POST})
public @ResponseBody ResponseEntity<byte[]> download(@PathVariable("time")String time) throws IOException { // 注此处必须使⽤ ClassPathResource⼯具类获取⽂件,避免在打包为jar⽂件部署时,不到⽂件路径的问题
ClassPathResource resource = new ClassPathResource("file/temp.xlsx");
String fileName = "temp_"+time;
ResponseEntity<byte[]> responseEntity = InputStream(), fileName);
return responseEntity;
}
/**
* ⽂件下载
* @param inputStream 传⼊⽂件流
* @param fileName ⽂件名
* @return ⽂件字节数据
* @throws IOException
*/
private ResponseEntity<byte[]> buildResponseEntity(InputStream inputStream, String fileName) throws IOException { //获取⽂件流
byte[] body = new byte[inputStream.available()];
HttpHeaders headers = new HttpHeaders();
//设置⽂件类型
headers.add("Content-Disposition", "attchement;filename=" + fileName);
//设置Http状态码
HttpStatus statusCode = HttpStatus.OK;
//返回数据
ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
return entity;
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论