欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

springBoot 文件上传与下载整合

程序员文章站 2022-09-29 21:51:36
Spring Boot 文件上传及下载方案controller文件上传部分注意:其中AjaxResult为返回封装类,这个类可有可无,开发环境下为了统一返回格式用 @PostMapping("/upload") public AjaxResult uploadFile(MultipartFile file) throws Exception { try { // 上传文件路径(这里最好配置在yml中,以方便后续修改 若为linux 可以直接写:"/ho...

Spring Boot 文件上传及下载方案

1.controller文件上传部分

注意:其中AjaxResult为返回封装类,这个类可有可无,开发环境下为了统一返回格式用

 	@PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            // 上传文件路径(这里最好配置在yml中,以方便后续修改 若为linux 可以直接写:"/home/upload/" ,具体地址,大家自己定就可以)
            String filePath = "D:/base/uploadPath"
           //获取上传的文件名称
         	String fileName = file.getOriginalFilename();
         	//构造路径,返回file对象
            File desc = new File(filePath + File.separator + fileName);
             if (!desc.getParentFile().exists()) {
            	desc.getParentFile().mkdirs();
       		 }
            //进行上传
            file.transferTo(desc);
            AjaxResult ajax = AjaxResult.success();
            //这里是将file的名称和路径返回到请求调用处
            ajax.put("fileName", fileName);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

2.controller文件下载部分

    /**
     * 本地资源通用下载
     */
    @GetMapping("/download")
    public void resourceDownload(@ApiParam(name = "name", value = "文件名称", required = true, type = "String")String name, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 本地资源路径
        String localPath = "D:/base/uploadPath"
        // 数据库资源地址
        String downloadPath = localPath +"/" +name;
        // 下载名称,这里浏览器不同,需要做的处理也不同;
        String encodeName = URLEncoder.encode(name, "utf-8");
        File file = new File(downloadPath);
        if (file.exists()) {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/force-download");
            response.addHeader("Content-Disposition", "attachment;fileName=" + encodeName);
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream outputStream = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    outputStream.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

关于根据浏览器设置返回名称的方法

public static String setFileDownloadHeader(HttpServletRequest request, String fileName)
        throws UnsupportedEncodingException
{
    final String agent = request.getHeader("USER-AGENT");
    String filename = fileName;
    if (agent.contains("MSIE"))
    {
        // IE浏览器
        filename = URLEncoder.encode(filename, "utf-8");
        filename = filename.replace("+", " ");
    }
    else if (agent.contains("Firefox"))
    {
        filename = new String(fileName.getBytes(), "ISO8859-1");
    }
    else if (agent.contains("Chrome"))
    {
        // google浏览器
        filename = URLEncoder.encode(filename, "utf-8");
    }
    else
    {
        // 其它浏览器
        filename = URLEncoder.encode(filename, "utf-8");
    }
    return filename;
}

关于对上传文件的直接url访问,需要映射目录路径,以D:/base/uploadPath 为例,

/**
 * 资源映射路径
 */
@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/temp-rainy/**").addResourceLocations("file:D:/base/uploadPath/");
    }
}

本文地址:https://blog.csdn.net/qq_33304139/article/details/110441887