java
@RequestMapping(value = "/downLoad", method = RequestMethod.POST)
public void downLoad(HttpServletResponse response) throws IOException {
//定义变量
String downPath = "";
ResourceLoader resourceLoader = new DefaultResourceLoader();
Resource resource = null;
byte[] buffer = new byte[1024];
InputStream inputStream = null;
BufferedInputStream bis = null;
OutputStream os = null; //输出流
try {
//获取resource中的文件,并生成流信息
resource = resourceLoader.getResource("classpath:excel/companyInfoImportExcel.xlsx");
inputStream = resource.getInputStream();
//设置返回文件信息
response.setContentType("application/octet-stream");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode("companyInfoImportExcel.xlsx", "UTF-8"));
//将内容使用字节流写入输出流中
os = response.getOutputStream();
bis = new BufferedInputStream(inputStream);
while (bis.read(buffer) != -1) {
os.write(buffer);
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally {
//关闭流信息
try {
if (inputStream != null) {
inputStream.close();
}
if (bis != null) {
bis.close();
}
if (os != null) {
os.flush();
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
模板位置
vue
handleDownLoad() {
// let url = 'http://localhost:9999/xxx/downLoad'
let url = `${window._CONFIG['baobiao']}/${this.url.download}`
const token = Vue.ls.get(ACCESS_TOKEN)
this.headers = { 'X-Access-Token': token }
this.axios({
method: 'post',
url: url,
responseType: 'blob',
data: [],
headers: { 'X-Access-Token': token },
})
.then((response) => {
//文件名 文件保存对话框中的默认显示
let fileName = '导入模板.xlsx'
let data = response
if (!data) {
return
}
console.log(response) //构造a标签 通过a标签来下载
let url = window.URL.createObjectURL(new Blob([data]))
let a = document.createElement('a')
a.style.display = 'none'
a.href = url //此处的download是a标签的内容,固定写法,不是后台api接口
a.setAttribute('download', fileName)
document.body.appendChild(a)
//点击下载
a.click()
// 下载完成移除元素
document.body.removeChild(a)
// 释放掉blob对象
window.URL.revokeObjectURL(url)
})
.catch((response) => {
this.$message.error(response)
})
// window.open(url)
},