springmvc實現文件下載

springmvc實現文件下載

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

第一種能夠直接向response的輸出流中寫入對應的文件流java

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

1、使用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形式給前臺返回提示信息。json

2、使用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;
        }
    }
}
相關文章
相關標籤/搜索