前端:调用该方法实现文件下载,前端你可以写个按钮调用该方法
async function submit() {
for (const id of form.value.fileList) {
const baseURL = import.meta.env.VITE_APP_BASE_API
var url = baseURL + `/download/${id}`//写你自己的文件下载接口
axios({
method: 'get',
url: url,
responseType: 'blob',
headers: { 'Authorization': 'Bearer ' + getToken() }
}).then((res) => {
const isBlob = blobValidate(res.data);
if (isBlob) {
const blob = new Blob([res.data])
saveAs(blob, decodeURIComponent(res.headers['download-filename']))
} else {
this.printErrMsg(res.data);
}
})
}
close();
}
后端:service层
public void downloadFile(String id, HttpServletResponse response){
try
{
Assert.notNull(id,()->new ServiceException("数据异常,请联系管理员"));
//获取该文件信息
FileInfo fileInfo = fileInfoService.getById(Long.parseLong(id));
// 本地资源路径
String localPath = RuoYiConfig.getProfile();
// 数据库资源地址
String downloadPath = (localPath + fileInfo.getFilePath()).replace("/profile","");
// 下载名称
String downloadName = fileInfo.getName();
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
//文件名(文件001_20240516140426A003.xlsx)
FileUtils.setAttachmentResponseHeader(response, downloadName);
//文件路径(/profile/upload/2024/05/16/文件001_20240516140426A003.xlsx)
FileUtils.writeBytes(downloadPath, response.getOutputStream());
}
catch (Exception e)
{
log.error("下载文件失败", e);
}
}