測試代碼
pom.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.2</version>
</parent>
<packaging>jar</packaging>
<groupId>com.kaven</groupId>
<artifactId>springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot</name>
<description>springboot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
檔案下載下傳接口:
package com.kaven.springboot.controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@RestController
public class FilesController {
@GetMapping("/download/{path}")
public void download(@PathVariable("path") String path ,
HttpServletResponse response){
// 将需要下載下傳的檔案對應到伺服器的本地檔案路徑
// 一般會使用雲存儲伺服器來存儲檔案,然後資料庫中儲存雲存儲伺服器中檔案的路徑
File file = new File("C:\\Users\\Kaven\\Desktop\\images\\" + path);
// 緩沖位元組數組
byte[] buffer = new byte[1024];
BufferedInputStream bis = null;
OutputStream os = null;
try {
// 檔案是否存在
if (file.exists()) {
// 設定響應
response.setContentType("application/octet-stream;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
// 擷取響應的輸出流
os = response.getOutputStream();
// 擷取檔案的輸入流
bis = new BufferedInputStream(new FileInputStream(file));
// 不斷将檔案輸入流中的位元組讀取到緩沖位元組數組中,直到檔案讀取完
while(bis.read(buffer) != -1){
// 将緩沖位元組數組中的位元組寫入響應的輸出流
os.write(buffer);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 關閉資源
if(bis != null) {
bis.close();
}
if(os != null) {
os.flush();
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
啟動類:
package com.kaven.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(SpringbootApplication.class);
application.run(args);
}
}
使用浏覽器進行測試,下載下傳的檔案在伺服器上存在,如下圖所示。
通路
http://localhost:8080/download/1.jpg
,會彈出如下圖所示的彈框。
圖檔檔案成功下載下傳到指定位置。
通路
http://localhost:8080/download/americanlie_testdetection.avi
下載下傳視訊(部落客的電腦預設會使用下載下傳器進行下載下傳)。
視訊檔案是完整的,可以播放。