vue部分前端代码
<el-table-column
prop="displayName"
min-width="100"
show-overflow-tooltip
header-align="center"
label="附件名称">
<template slot-scope="scope">
<el-link style="color: #409eff;cursor: pointer" @click="downLoadFile(scope.row)">
{{scope.row.displayName}}
</el-link>
</template>
</el-table-column>
downLoadFile(rowData) {
// 不用ajax请求,而是用普通的方式 这是重点!
let basePath = gbs.host + gbs.adminContext + '/knowlgAttach/downloadFile'
let exportParams = {kaId: rowData.kaId, displayName: rowData.displayName};
let path = basePath + "?param=" + encodeURI(JSON.stringify(exportParams));
window.location.href = path;
}
java后端代码
@RestController
@RequestMapping("/knowlgAttach")
public class KnowlgAttachController {
@RequestMapping("/downloadFile")
public void downloadFile(HttpServletResponse resp, @RequestParam String param) throws Exception {
KnowlgAttachDomain item = JSON.parseObject(param,KnowlgAttachDomain.class);
// 从es中获取文件信息 SFFile的父类是File
// 大致过程是从es中获取文件加载到本地缓存 SFFile存储文件路径等信息
// 本质就是加载本地缓存中的文件内容并且通过响应(下载)的方式读取,来达到下载的过程
SFFile file = imFileService.getFile(item.getKaId());
String name = item.getDisplayName();
String[] arr = name.split("\\.");
String type = arr[1];
resp.reset();
// 设置响应方式
resp.setContentType("application/x-download");
resp.setCharacterEncoding("utf-8");
// 下载文件名中文乱码处理
resp.setHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes("gbk"), "iso8859-1") + "." + type);
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(file);
output = resp.getOutputStream();
byte[] b = new byte[4096];
int i = 0;
while ((i = input.read(b)) > 0) {
output.write(b, 0, i);
}
output.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
file.delete();
IOUtils.closeQuietly(input);
IOUtils.closeQuietly(output);
}
}
}