Java spring實現文件下載


一,實現目的,后台寫一個controller,然后前台頁面點擊文件下載,實現文件下載功能。(文件是存放於服務器的磁盤上的)

@RequestMapping("/filesdownloads")
        public ResponseEntity<byte[]> EIToolDownloads(HttpServletRequest request,HttpServletResponse response) throws IOException{
     String doenLoadPath = "xxx";  // doenLoadPath是文件路徑(一般指服務器上的磁盤位置)
        File file = new File(doenLoadPath);
        if(file.exists()){
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                headers.setContentDispositionFormData("attachment", file.getName());
                return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.OK);
            }else{
                System.out.println("文件不存在,請重試...");
                return null;
            }
        }

二,前台只需要一個a標簽即可:

HTML代碼:
<a href="/filesdownloads" >下載</a>

 三,前台也可以通過點擊button觸發下載功能

//js代碼
function download(){
               self.location.href("/filesdownloads");
              
        }


//html代碼
<button onclick="download()"></button>

 


免責聲明!

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



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