在這篇博客中,我們將展示如何在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目錄,如下:
So, 用Spring Boot實現文件下載功能搞定!歡迎大家交流哦~
注意:本人現已開通兩個微信公眾號: 因為Python(微信號為:python_math)以及輕松學會Python爬蟲(微信號為:easy_web_scrape), 歡迎大家關注哦~~