zoukankan      html  css  js  c++  java
  • 下载文件出现内存溢出问题

    现场还原,一下是下载大文件出现内存溢出的代码:

        @RequestMapping(value = "/downLoadBackupFile")
        public ResponseEntity<byte[]> downloadBackupFile(Integer id, HttpServletResponse response) throws Exception{
            String path = eqm.findAddr(id);
            File file = new File(path);
            String fileName = file.getName();
            byte[] body = null;
            InputStream is = new FileInputStream(file);
            body = new byte[is.available()];                                            // 报错显示该行出现内存溢出问题,new了一个非常大的byte数组
            is.read(body);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attchement;filename=" + fileName);
            HttpStatus statusCode = HttpStatus.OK;
            ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
            return entity;
        }
    

    应该修改为:

    @RequestMapping(value = "/downLoadBackupFile", method = RequestMethod.GET)
        public void downloadBackupFile(Integer id, HttpServletResponse response) throws Exception{
            String path = eqm.findAddr(id);
            File file = new File(path);
            String fileName = file.getName();
    
            response.reset();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attchement;filename=" + fileName);
            response.setHeader("Content-Length", file.length() + "");
    
            InputStream bfis = new BufferedInputStream(new FileInputStream(file));
            OutputStream ops = new BufferedOutputStream(response.getOutputStream());
            byte[] body = new byte[1024];
            int i = -1;
            while ((i = bfis.read(body)) != -1){
                ops.write(body, 0, i);
            }
            bfis.close();
            ops.flush();
            ops.close();
        }
    
  • 相关阅读:
    angularjs中设置select的选中项
    axios 下载文件
    解决Springboot集成ActivitiModel提示输入用户名密码的问题
    VMWare14 安装Mac OS系统(图解)
    hexo 搜索功能
    Nginx禁止IP直接访问网站
    不确定理论与多传感器数据融合
    Bayes理论与多传感器数据融合
    从“中英文思维回译法”看中英思维差异
    不确定理论与多传感器数据融合
  • 原文地址:https://www.cnblogs.com/theone67/p/10937330.html
Copyright © 2011-2022 走看看