vue前端代码
methods: {
getfile() {
this.ylLoading = true;
const userReqData = {
contractNum: this.formObj.contractNum
}
crudBilling.getfile(userReqData).then(res => {
this.ylLoading = false;
let blob = new Blob([res], {
type: 'application/pdf'
})
let fileName = Date.parse(new Date()) + '.pdf'
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, fileName)
} else {
var link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = fileName
window.open(link)
window.URL.revokeObjectURL(link.href)
}
}).catch(message => {
this.ylLoading = false;
});
}
}
springboot接口代码
@NeedLog
@GetMapping("/getFile")
@PreAuthorize("@el.check('contract:getFile')")
public void getFile(@RequestParam Long id,HttpServletResponse response)throws Exception{
contractService.getFile(id,response);
}
@Override
public void getFile(Long id, HttpServletResponse response) throws Exception {
Contract contract = contractRepository.findById(id);
if (contract == null) {
return;
}
String url = contract.getUrl();
File file = new File(url);
if (file.exists()) {
response.addHeader("Content-Disposition", "inline;fileName=" + java.net.URLEncoder.encode(file.getName(), "UTF-8"));
response.setContentType("application/octet-stream;");
response.setHeader("Content-Length",""+file.length());
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
byte[] buff = new byte[1024];
OutputStream os = response.getOutputStream();
try {
int i;
while ((i = bis.read(buff)) != -1) {
os.write(buff, 0, i);
}
} catch (IOException e) {
log.error("下载pdf异常", e);
} finally {
os.flush();
os.close();
}
}
}