前端

<el-button 
  type="success"
  icon="el-icon-download"
  @click="downloadTemplate">下载模板</el-button>
//下载模板
downloadTemplate(){
const fileName = '药品清单-模板.xlsx'
medicineListApi.fileDownload({
fileName,
inResource: true,
}).then(res => {
fileDownload(res.data, fileName)
}, err => { console.log(err) })
}

medicineList.js中代码

//下载文件
fileDownload(query) {
return request({
url: baseUrl + '/fileDownload',
method: 'post',
data: query,
responseType: 'arraybuffer'
})
},

后台代码:

controller

@PostMapping("/fileDownload")
public void fileDownload(@RequestBody JSONObject jsonObject, HttpServletResponse response) throws Exception {
Boolean inResource = jsonObject.getBoolean("inResource");
String fileName = jsonObject.getString("fileName");
if (inResource) {
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("template/" + fileName);
ExcelUtil.downloadFile(fileName, stream, response);
}
}

工具类的downloadFile方法

public static void downloadFile(String filename, InputStream in, HttpServletResponse response) throws IOException {
//设置浏览器直接下载文件,不打开,并设置文件名的编码
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
int len = 0;
byte bytes[] = new byte[1024];
OutputStream out = response.getOutputStream();
while ((len = in.read(bytes)) > 0) {
out.write(bytes, 0, len);
}
in.close();
}

 

posted on 2020-09-28 17:34  周文豪  阅读(252)  评论(0)    收藏  举报