后端代码:
@RequestMapping("/download/test") public void download(HttpServletResponse response,@RequestBody ProjectHistory projectHistory){ response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=license.lic"); ProjectHistory serviceById = historyService.getById(projectHistory.getId()); ///文件路径 String licenseFilePath = serviceById.getLicenseFile(); try { FileInputStream is = new FileInputStream(licenseFilePath); byte[] temp = new byte[is.available()]; is.read(temp); response.getOutputStream().write(temp); is.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
前端代码:
<template slot-scope="scope"> <el-button @click="download(scope.row.id)" type="text" size="small">下载文件</el-button> </template>
async download(id){ const res = await this.downFile('www.baidu.com',{id:'00'}){ let blob = new Blob([res.data]); let link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = '文件名称.txt'; link.click(); link.remove(); } } downFile(url,params){ const result = axios.post(url,params,{responseType:'blob'}).then(res =>{ return res; }); return result; }