本篇文章仅针对ruoyi模板的下载文件功能,对其进行修改
前端
注意事项
1.不要用ajax传参,可以使用 location.href的方式,使用ajax调用Controller不会开启下载文件弹窗,但是会正常下载文件,控制台也不会报错,下载好的文件会在浏览器中的network中的最新一条请求中的response中找到二进制文件数据
filename均为/profile/upload开头
2.ruoyi数据库储存的所有文件路径统一有五级,
文件路径举例:/profile/upload/2021/05/10/xxx.jpg
3.在后端Controller中解决路径字符串中带有斜杠的问题,解决方法为:将每一级路径都作为参数进行传递。
写法
var filename = "/profile/upload/2021/05/10/xxx.jpg",
function download(filename) {
$.modal.confirm("确定要文件下载吗?", function() {
//将路径名一部分/upload/2021/05/10/xxx.jpg传给controller
location.href = ctx+'common/download/resource'+filename.substring(filename.lastIndexOf("/upload"));
});
}
后端
修改ruoyi CommonController中的common/download/resource
注意事项
1.将ruoyi的getDownloadPath()变换为getProfilePath(),因为上传的文件都会储存在profile/upload下,而原ruoyi的通用下载是在profile/download下,然而没有文件会上传在download文件夹下,这就会有矛盾,所以我们修改一下Controller中获取path的方法。
2.由于原downloadPath只能取出在ruoyi-admin中application.yml取到的profile文件路径,所以要在写文件方法FileUtils.writeBytes()中传入的文件路径修改为全路径+文件名,否则会出现拒绝访问的情况
Controller写法
/**
* 本地资源通用下载
*/
@Log(title = "文件下载", businessType = BusinessType.OTHER)
@GetMapping("/common/download/resource/upload/{year}/{month}/{day}/{filename}")
public void resourceDownload2(@PathVariable("year") String year,
@PathVariable("month") String month,
@PathVariable("day") String day,
@PathVariable("filename") String resource, HttpServletResponse response)
throws Exception
{
//还要传三个值,从第三个斜杠开始\2021\05\09
//downloadPath加/upload
try
{
if (!FileUtils.checkAllowDownload(resource))
{
throw new Exception(StringUtils.format("资源文件({})非法,不允许下载。 ", resource));
}
// 本地资源路径
String localPath = RuoYiConfig.getProfile();//这里的getProfile不
// 数据库资源地址
String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
// 下载名称
//String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
//response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);//二进制文件
response.setHeader("Content-Disposition", "attachment; filename="+resource);
response.setContentType("application/octet-stream; charset=UTF-8");
FileUtils.setAttachmentResponseHeader(response, resource);
System.out.println("downloadPath:"+downloadPath);
FileUtils.writeBytes(downloadPath+"/upload/"+year+"/"+month+"/"+day+"/"+resource, response.getOutputStream());
}
catch (Exception e)
{
log.error("下载文件失败", e);
}
}