利用springboot 重定向到静态资源功能,下载一些文件文件

1、首先在配置文件添加项目外资源文件定位:

  

spring:
  web:
    resources:
      static-locations:  file:uploads/,classpath:static/    #手动设置项目外路径uploads

2、我们可以在项目文件家中创建uploads文件夹,以后项目jar外面也有uploads文件夹,该文件夹放置我们要下载的文件:

    ,,,,

3、控制层定义 下载文件接口:

@Controller
public class DownClass {

    /**
     * 下载app
     * @param response
     * 解释一下,我们在yml里面配置了地址uploads,并且也在项目的根路径(直接在文件夹中,而不是IDEA工具里面)创建uploads/xxx.apk文件。
     */
    @RequestMapping("downApp")
    @ResponseBody
    public void Download(HttpServletResponse response,String version) {
        File directory = new File("");// 参数为空
        String courseFile = "";
        String fileName = "test-"+version+".apk";
        try {
            courseFile = directory.getCanonicalPath();
            System.out.println("path2: "+courseFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String filepath = courseFile+"\uploads\" + fileName;
        File path = new File(filepath);
        if (!path.exists()) {
            System.out.println("找不到该文件:" + fileName);
            return;
        }else{
            try {
                response.sendRedirect("/" + fileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

1、首先查询该文件是否存在,文件名 + 版本号。

2、存在则利用response.sendRedirect("/" + fileName)  重定向到该文件。

其实就是静态资源访问罢。

原文地址:https://www.cnblogs.com/hcklqy/p/14836031.html