1、后端代码
参数response 是文件流传输必须的,
然后chatFileParam是业务需要用来获取服务器文件的,你们可以不看,不写
/**
* 页面下载文件
* @param response
* @param chatFileParam
*/
@ApiOperation(value = "页面下载文件")
@PostMapping("downFileForWeb")
public void downFileForWeb(HttpServletResponse response, @RequestBody ChatFileParam chatFileParam) {
try {
// 获取本地文件 你们可以通过FileInputStream(文件路径)获取File对象
if (StringUtils.isEmpty(chatFileParam.getUrlStr())){
throw new IllegalArgumentException("文件路径不存在!");
}
File file = cosFileService.download(chatFileParam.getUrlStr());
// 下面是获取文件流并发送给前端,response会将文件流发送给前端
response.setCharacterEncoding("UTF-8");
if (file == null || !file.exists()){
throw new IllegalArgumentException("文件不存在!");
}
String simpleName = file.getName().substring(file.getName().lastIndexOf("/") + 1);
String newFileName = new String(simpleName.getBytes(), StandardCharsets.UTF_8);
response.setHeader("Content-disposition", "attachment;filename=" + newFileName);
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(file));
BufferedOutputStream bos = new BufferedOutputStream(
response.getOutputStream());
byte[] buffer = new byte[1024];
int length;
while ((length = bis.read(buffer)) != -1) {
bos.write(buffer, 0, length);
}
bis.close();
bos.close();
} catch (InterruptedException | IOException | IllegalArgumentException e) {
e.printStackTrace();
}
}
}
2、前端点击后下载文件
代码
首先是访问后台请求
export function downFile(params){
return request({
method: 'post',
url: '/tfapp/chatFile/downFileForWeb',
responseType:'blob',//接收的文件流对象,很重要
data: params //业务需要传递的参数
});
}
页面点击事件调用
import {downFile} from "@/api/chat";
downFile(fileName) {
console.log('文件名',fileName)
// 解析文件名
content.split("\">")
const result = await downFile(params);
let url = window.URL.createObjectURL(result)
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', fileName)
document.body.appendChild(link)
link.click()
}
调用downFile请求时,返回的时Blob对象,如下图所示
3、效果