实现效果:点击链接,下载对应文件
后端接口:
import com.example.admin.entity.FileEntity;
import com.example.admin.service.FileService;
import com.example.admin.utils.Result;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
@RestController
@RequestMapping("/file")
public class FileController {
@Autowired
private FileService fileService;
// 根据文件id查询文件信息
@GetMapping("/getFile")
public Result<FileEntity> getFile(String fid) {
return fileService.getFileById(fid);
}
// 文件下载
@GetMapping("/download")
public void fileDownload(String fid, HttpServletResponse response) throws IOException {
FileEntity fileEntity = fileService.getFileById(fid).getData();
String fname = fileEntity.getFname();
String path = fileEntity.getPath();
File file = new File(path);
FileInputStream is = new FileInputStream(file);
response.setContentType("application/x-download;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fname, "UTF-8"));
ServletOutputStream os = response.getOutputStream();
IOUtils.copy(is, os);
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}
}
前端代码:
<el-table-column label="下载文件" prop="licence1">
<template slot-scope="scope">
<!-- 使用 scoped slot 自定义单元格内容 -->
<el-link @click="download(scope.row.licence1)">
{{ scope.row.licence1 }}
</el-link>
</template>
</el-table-column>
/* 下载文件 */
async download(fid) {
try {
const response = await this.$axios.get("/api/file/download", {
params: {
fid: fid,
},
responseType: "arraybuffer",
});
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement("a");
link.href = url;
// 获取文件信息
const fileInfoResponse = await this.$axios.get("/api/file/getFile", {
params: {
fid: fid,
},
});
const fname = fileInfoResponse.data.data.fname;
link.setAttribute("download", `${fname}`);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
} catch (error) {
console.error("Download error:", error);
}
},