SpringMvc 文件下载的两种方式

方式一:通过reponse的输出流

 @RequestMapping("/d1")
    public ResultVo<String> downloadFile(HttpServletResponse response){

        String fileName="test1.png";
        try {
            //获取response的输出流
            ServletOutputStream outputStream = response.getOutputStream();
            //读取文件
            byte[] bytes = FileUtils.readFileToByteArray(new File("D:\\test.png"));
            response.setHeader("Content-Disposition","attachment;filename="+fileName);
            //写入到输出流
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();
            return ResultVoUtil.success("success");
        } catch (IOException e) {
            return ResultVoUtil.error(e);
        }

    }

方式二:通过返回ResponseEntity

@GetMapping("/d2")
    public ResponseEntity<byte[]> download2(){
        //获取文件对象
        try {
            byte[] bytes = FileUtils.readFileToByteArray(new File("D:\\test2.png"));
            HttpHeaders headers=new HttpHeaders();
            headers.set("Content-Disposition","attachment;filename=test2.png");
            ResponseEntity<byte[]> entity=new ResponseEntity<>(bytes,headers,HttpStatus.OK);
            return entity;
        } catch (IOException e) {
            logger.error("下载出错:",e);
            return null;
        }
    }

 

上一篇:扶风解析计费系统源码 1.7.1视频解析 短视频解析 影视视频电影解析计费平台源码程序


下一篇:springboot 统一json返回格式,并设置http响应码