1. 程式人生 > >Spring Boot實現檔案下載功能

Spring Boot實現檔案下載功能

我們只需要建立一個控制器(Controler)檔案,即Controller目錄下的File_Download.java,其完整目錄如下:

@Controller
public class File_Download {

    //實現Spring Boot 的檔案下載功能,對映網址為/download
    @RequestMapping("/download")
    public String downloadFile(HttpServletRequest request,
                               HttpServletResponse response) throws UnsupportedEncodingException {

        // 獲取指定目錄下的第一個檔案
        File scFileDir = new File("E://music_eg");
        File TrxFiles[] = scFileDir.listFiles();
        System.out.println(TrxFiles[0]);
        String fileName = TrxFiles[0].getName(); //下載的檔名

        // 如果檔名不為空,則進行下載
        if (fileName != null) {
            //設定檔案路徑
            String realPath = "E://music_eg/";
            File file = new File(realPath, fileName);

            // 如果檔名存在,則進行下載
            if (file.exists()) {

                // 配置檔案下載
                response.setHeader("content-type", "application/octet-stream");
                response.setContentType("application/octet-stream");
                // 下載檔案能正常顯示中文
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

                // 實現檔案下載
                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);
                    }
                    System.out.println("Download the song successfully!");
                }
                catch (Exception e) {
                    System.out.println("Download the song failed!");
                }
                finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }

}

這樣我們就完成了Spring Boot的檔案下載功能。

執行Spring Boot專案後,在瀏覽器中輸入:http://localhost:8080/download , 你會發現什麼?那就是你的瀏覽器已經開始下載E盤music_eg目錄下的某一個檔案啦(前提是E盤中存在music_eg目錄,當然裡面還得有檔案,本例僅作為測試),如下圖所示:

檔案下載