Java 安全 后端返回文件流

Java 安全 后端返回文件流,第1张

Java 安全 后端返回文件流 1,起由

业务流程:上传文件——服务器保存文件——根据路径访问文件

这种根据路径定位文件,并对文件进行查看的方式对文件安全有很大威胁,一旦知道其他文件的路径,很有可能会造成文件泄露

2,改进

所以,当前端访问文件的时候,发出请求并携带token,后端验证token,确认为合法用户之后,放行

根据请求路径执行后端的代码(后端代码逻辑:根据路径读取文件,输出文件流,响应给前端)

3,配置文件

配置上存文件的保存路径

4,代码:
	import org.apache.commons.io.IOUtils;

    @Value("${file.ectdreport-folder}")
    private String ectdReportFolder;


    @Transactional(rollbackFor = Exception.class)
    public void lookReport(String id, HttpServletResponse response) throws Exception {

        String url = ectdReportFolder + id + "/file1.html";
        File file = new File(url);
        if (!file.exists()) {
            throw new Exception("文件不存在");//抛出文件不存在的
        }
        response.setContentType("text/html");
        FileInputStream fis = null;
        OutputStream outputStream = response.getOutputStream();
        try {
            fis = new FileInputStream(file);
            //将读取流拷贝到输出流中
            IOUtils.copy(fis, outputStream);
            //清空缓存的读取流,保证数据完整性
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
           throw new Exception("解析失败");
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                outputStream.close();//输出流关闭
            }
        }
    }

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5683209.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存