栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java 安全 后端返回文件流

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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();//输出流关闭
            }
        }
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/682643.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号