springmvc實現文件下載


springmvc實現文件下載

使用springmvc實現文件下載有兩種方式,都需要設置response的Content-Disposition為attachment;filename=test2.png

第一種可以直接向response的輸出流中寫入對應的文件流

第二種可以使用 ResponseEntity<byte[]>來向前端返回文件

一、使用response


@RestController
@RequestMapping("/download")
public class DownloadController {

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

        String fileName="test.png";
        try {
            //獲取頁面輸出流
            ServletOutputStream outputStream = response.getOutputStream();
            //讀取文件
            byte[] bytes = FileUtils.readFileToByteArray(new File("D:\\my-study\\test2.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);
        }

    }
}

推薦使用這種方式,這種方式可以以json形式給前台返回提示信息。

二、使用ResponseEntity


@Controller
@RequestMapping("/download2")
public class DownloadController2 {

    private final static Logger logger= LoggerFactory.getLogger(CategoryDataController.class);


    @GetMapping("/d2")
    public ResponseEntity<byte[]> download2(){
        //獲取文件對象
        try {
            byte[] bytes = FileUtils.readFileToByteArray(new File("D:\\my-study\\bill-admin\\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;
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM