后台controller
@GetMapping("/DownloadWorkorderFile")
@ResponseBody
public void DownloadWorkorderFile(HttpServletRequest request, HttpServletResponse response, String filePath){
File file = new File(filePath);
String fileName = file.getName();
InputStream fis = null;
try {
fis = new FileInputStream(file);
request.setCharacterEncoding("UTF-8");
String agent = request.getHeader("User-Agent").toUpperCase();
if ((agent.indexOf("MSIE") > 0) || ((agent.indexOf("RV") != -1) && (agent.indexOf("FIREFOX") == -1)))
fileName = URLEncoder.encode(fileName, "UTF-8");
else {
fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
}
response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/force-download");
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
response.setHeader("Content-Length", String.valueOf(file.length()));
byte[] b = new byte[1024];
int len;
while ((len = fis.read(b)) != -1) {
response.getOutputStream().write(b, 0, len);
}
response.flushBuffer();
fis.close();
}catch (IOException e) {
throw new RuntimeException(e);
}
}
前端Vue
<template>
<div>
<el-button type="primary" @click="download">下载</el-button>
</div>
</template>
<script>
export default {
data() {
return {
};
},
methods: {
download() {
var path = '/home/axs-spring/data/ceshi.png';
window.open("http://localhost:8041/Management/DownloadWorkorderFile?filePath=" + encodeURI(path));
},
}
};
</script>