前言:
在使用FastDFS作为文件服务器时,我们肯定遇到过文件下载问题,当下载地址与FastDFS属与同一台服务器时,下载文件很容易实现,但是当下载地址与FastDFS不属于同一台服务器时,需要通过浏览器来辅助进行下载到本地。
1.后台示例接口代码:
public ResponseEntity<byte[]> downloadFile(@RequestParam("id") Integer id ) {
//根据id查找附件信息
MessageAttachment messageAttachment = attachmentService.getById(id);
// http://192.168.23.222:7099/group1/M00/00/02/wKgX3l8-F9KABdUlAAP5BN0hxz4168.pdf
String s = messageAttachment.getFileUrl();
//以“/”切割4次
String[] ss = s.split("/", 5);
//根据fastdfs上传组别以及资源名称得到下载字节数组 ss[3]:group1 ss[4]:M00/00/02/wKgX3l8-F9KABdUlAAP5BN0hxz4168.pdf
//目的是得到字节数组
byte[] fileBuff = FastDFSClient.downloadFile(ss[3], ss[4]);
// 设置下载信息头文件
String downloadName = messageAttachment.getOriginalName();
String contentType = "application/octet-stream";
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(contentType))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + downloadName + "\"")
.body(fileBuff);
}
2.vue调用示例代码:
<el-button class="mail-btn" @click="downloadFile(messageInfo.id)">下载</el-button>
//下载邮件附件文件
downloadFile(row) {
let params = {
id: this.messageInfo.fileId,
};
api.downloadFile(params).then((respond) => {
if (respond.status === 200) {
let respondData = respond.data;
var blob = new Blob([respondData], {
type: "application/octet-stream",
});
var link = document.createElement("a");
link.download = this.messageInfo.fileName;//下载文件名
link.href = window.URL.createObjectURL(blob);
document.body.appendChild(link);
link.click();
window.URL.revokeObjectURL(link.href);
}
});
},
3.实现效果:
若对fastdfs有疑问的可以参照我的另外一篇博客:SpringBoot整合FastDFS实现文件的上传与下载(详解+扩展)