记SpringBoot下载的两种方式

记SpringBoot下载的两种方式

  • 使用流来进行下载
  • 通过配置本地资源映射路径 addResourceHandlers,来实现下载

最近接了个任务,实现文件的下载,自己做了好久才做完,有乱码问题,有文件损坏问题,还有框架之间冲突。。。( SpringBoot下载有问题?看这一篇就够了)最开始我是用 来实现下载的,后面我师傅说,有更加简单的方式。。。。。。结果他就用了 几行代码就完事了。。。。
我:

记SpringBoot下载的两种方式_第1张图片

使用流来进行下载

这种方式就比较常见了,网上大部分的文章都是采取该方式来实现下载的。

public synchronized void downloadFile(String path , HttpServletResponse response) throws Exception {
        //确保下载路径包含download关键字(确保下载内容,在download文件夹下)
        if(path.contains("download")) {
            File file = new File(path);
            String filename = file.getName();
            //获取文件后缀
            String extension = getNameOrExtension(filename , 1);
            //设置响应的信息
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" +  URLEncoder.encode(filename, "utf8"));
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            //设置浏览器接受类型为流
            response.setContentType("application/octet-stream;charset=UTF-8");

            try(
                    FileInputStream in = new FileInputStream(file);
            ) {
                // 将文件写入输入流
                OutputStream out = response.getOutputStream();

                if("doc".equals(extension)) {
                    //doc文件就以HWPFDocument创建
                    HWPFDocument doc = new HWPFDocument(in);
                    //写入
                    doc.write(out);
                    //关闭对象中的流
                    doc.close();
                }else if("docx".equals(extension)) {
                    //docx文件就以XWPFDocument创建
                    XWPFDocument docx = new XWPFDocument(in);
                    docx.write(out);
                    docx.close();
                } else {
                    //其他类型的文件,按照普通文件传输 如(zip、rar等压缩包)
                    int len;
                    //一次传输1M大小字节
                    byte[] bytes = new byte[1024];
                    while ((len = in.read(bytes)) != -1) {
                        out.write(bytes  , 0 , len);
                    }
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        } else {
            throw new Exception("下载路径不合法。");
        }

    }

如果有乱码问题,或者文件损坏,大家可以参考以下这一篇
SpringBoot下载有问题?看这一篇就够了

通过配置本地资源映射路径 addResourceHandlers,来实现下载

先创建一个继承WebMvcConfigurerAdapter子类,添加上注解,以下的方式进行配置
(当然我用的框架很老,如果没有这个类的话,参考这一篇文章
WebMvcConfigurerAdapter 在Spring5.0已被废弃)

@Configuration
public class MyConfig extends WebMvcConfigurerAdapter{
	//application.yml中映射的路径
	@Value(value = "${root.file.path}")
    private String rootFilePath;
	
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
	//配置file映射 访问时使用地址:端口/file/文件相对地址
	        registry.addResourceHandler("/file/**").addResourceLocations("file:"+rootFilePath);
        super.addResourceHandlers(registry);
    }
}

新版本的话是通过实现类WebMvcConfigurer ,来达到相同的目的

@Configuration
public class MyConfig implements WebMvcConfigurer {
    @Value(value = "${root.file.path}")
    private String rootFilePath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/file/**").addResourceLocations("file:"+ rootFilePath);
    }

}

application.yml里面配置上述的rootFilePath

root:
  file:
    path: D:\download\

然后实现的方式是:
比如,download目录下的文件结构是:
记SpringBoot下载的两种方式_第2张图片
现在我要下载测试文档.doc 浏览器直接输入

http://localhost:8080/file/测试文档.doc

回车访问即可 实现下载。

你可能感兴趣的:(常用的工具,框架,spring,boot,java,后端)