1. 程式人生 > >Spring Boot入門(11)實現檔案下載功能

Spring Boot入門(11)實現檔案下載功能

  在這篇部落格中,我們將展示如何在Spring Boot中實現檔案的下載功能。
  還是遵循筆者寫部落格的一貫風格,簡單又不失詳細,實用又能讓你學會。
  本次建立的Spring Boot專案的主要功能為檔案下載,而且這也是唯一功能,當然,作為例子,要儘可能簡單,所以,功能簡化為只下載E盤music_eg目錄下的某一個檔案。
  該Spring Boot專案的名稱為file_download,其具體結構如下:


專案結構

build.gradle檔案的程式碼如下:

buildscript {
    ext {
        springBootVersion = '2.0.3.RELEASE'
} repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' apply plugin: 'io.spring.dependency-management'
group = 'com.example' version = '0.0.1-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile('org.springframework.boot:spring-boot-starter-web') testCompile('org.springframework.boot:spring-boot-starter-test') }

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

package com.example.file_download.Controller;

import java.io.*;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@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目錄,當然裡面還得有檔案,本例僅作為測試),如下圖所示:


檔案下載

  我們再去檢視E盤music_eg目錄,如下:

E盤music_eg目錄

  So, 用Spring Boot實現檔案下載功能搞定!歡迎大家交流哦~

注意:本人現已開通兩個微信公眾號: 因為Python(微訊號為:python_math)以及輕鬆學會Python爬蟲(微訊號為:easy_web_scrape), 歡迎大家關注哦~~