springboot访问服务器文件功能详解(下载、预览)

springboot访问linux服务器文件并实现下载或预览

方式有两种:
方式1:通过HttpServletResponse输出流实现文件的下载和预览
方式2:通过实现WebMvcConfigurer接口实现文件预览

方式1

public static void downloadFile(File file, HttpServletResponse response) {
        String filePath = file.getPath();
        String filename = file.getName();
        ServletOutputStream outputStream = null;
        BufferedInputStream bufferedInputStream = null;
        try {
            outputStream = response.getOutputStream();
            // inline为预览
            response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(filename, "UTF-8"));
            // attachment为文件下载
//            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            // 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            // 如果设置此请求头,则为下载
//            response.setContentType("application/octet-stream");
            bufferedInputStream = new BufferedInputStream(new FileInputStream(filePath));
            byte[] bytes = new byte[1024 * 1024];
            int b = 0;
            while ((b = bufferedInputStream.read(bytes)) != -1) {
                outputStream.write(bytes);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bufferedInputStream.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

此方式下载和预览区别在于响应头的设置:

1. 以附件形式下载

①设置请求头content-Disposition为attachment
②或者设置content-type为application/octet-stream,目的是告诉浏览器这是一个字节流,浏览器处理字节流的默认方式就是下载(此方法可以设置Content-Disposition,也可以不设置)

2. 文件预览

文件预览仅适用文件格式为jpg、pdf、txt等文件格式,其他格式文件直接以附件形式下载。
①设置请求头content-Disposition为inline,并且不能设置content-type为application/octet-stream,否则会以附件形式下载。

方式2

@Configuration
public class MyWebMVCConfig implements WebMvcConfigurer {
    String fileLocation1 = "C:/Users/eiji/Desktop/";
    String fileLocation2 = "/data/webfiles/";

    String filePath = "/file/**";

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 匹配到resourceHandler,将URL映射至location,也就是本地文件夹
        registry.addResourceHandler(filePath).addResourceLocations("file:" + fileLocation1);
        // 可以添加多个映射
        registry.addResourceHandler(filePath).addResourceLocations("file:" + fileLocation2);

    }
}

此方式针对文件格式为image、pdf、txt直接展示在网页上,其他文件格式直接下载。

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值