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();//输出流关闭
            }
        }
    }
  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值