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直接展示在网页上,其他文件格式直接下载。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐