Spring-mvc後臺下載功能的兩種實現

@GetMapping("getInspFile")
    @ResponseBody
    public ResponseEntity<byte[]> getInspFile(HttpServletRequest request) throws IOException {
        String path="c://1.txt";
        File file = new File(path);        
        if(!file.exists()){return null;}        

        byte[] body;
        InputStream is = new FileInputStream(file);
        body = new byte[is.available()];
        is.read(body);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attchement;filename=" + file.getName());
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
        return entity;
    }

或者傳統的respon

 @GetMapping("getInspFile")
    public String getInspFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String path="c://1.txt";
        File file = new File(path);        
        if(!file.exists()){return null;}        

        if (file.exists()) {
            response.setContentType("application/force-download");// 設置強制下載不打開
            response.addHeader("Content-Disposition", "attachment;fileName=" + file.getName());// 設置文件名
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                return "下載成功";
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return "文件下載失敗";
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章