以下是用 Spring Boot 3 构建的文件上传和读取接口示例代码:
确保在 pom.xml 文件中添加了以下依赖:
pom.xml
xml 复制代码 <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
我们将文件上传到本地文件夹,例如 uploads/,然后通过文件名读取。
uploads/
配置上传文件的存储路径。
java 复制代码 package com.example.fileupload.config; import org.springframework.context.annotation.Configuration; import org.springframework.beans.factory.annotation.Value; @Configuration public class FileUploadConfig { @Value("${file.upload-dir:uploads/}") private String uploadDir; public String getUploadDir() { return uploadDir; } }
package com.example.fileupload.config; import org.springframework.context.annotation.Configuration; import org.springframework.beans.factory.annotation.Value; @Configuration public class FileUploadConfig { @Value("${file.upload-dir:uploads/}") private String uploadDir; public String getUploadDir() { return uploadDir; } }
实现上传和读取文件的 REST API。
java 复制代码 package com.example.fileupload.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import com.example.fileupload.config.FileUploadConfig; @RestController @RequestMapping("/api/files") public class FileController { private final String uploadDir; @Autowired public FileController(FileUploadConfig fileUploadConfig) { this.uploadDir = fileUploadConfig.getUploadDir(); File dir = new File(uploadDir); if (!dir.exists()) { dir.mkdirs(); // 创建上传目录 } } // 上传文件接口 @PostMapping("/upload") public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("File is empty"); } try { // 保存文件到指定路径 String fileName = file.getOriginalFilename(); Path filePath = Paths.get(uploadDir, fileName); Files.write(filePath, file.getBytes()); return ResponseEntity.ok("File uploaded successfully: " + fileName); } catch (IOException e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body("File upload failed: " + e.getMessage()); } } // 获取文件接口 @GetMapping("/{fileName}") public ResponseEntity<byte[]> getFile(@PathVariable String fileName) { try { Path filePath = Paths.get(uploadDir, fileName); byte[] fileContent = Files.readAllBytes(filePath); // 设置文件响应头 HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\""); headers.add(HttpHeaders.CONTENT_TYPE, Files.probeContentType(filePath)); return ResponseEntity.ok() .headers(headers) .body(fileContent); } catch (IOException e) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); } } }
package com.example.fileupload.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import com.example.fileupload.config.FileUploadConfig; @RestController @RequestMapping("/api/files") public class FileController { private final String uploadDir; @Autowired public FileController(FileUploadConfig fileUploadConfig) { this.uploadDir = fileUploadConfig.getUploadDir(); File dir = new File(uploadDir); if (!dir.exists()) { dir.mkdirs(); // 创建上传目录 } } // 上传文件接口 @PostMapping("/upload") public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("File is empty"); } try { // 保存文件到指定路径 String fileName = file.getOriginalFilename(); Path filePath = Paths.get(uploadDir, fileName); Files.write(filePath, file.getBytes()); return ResponseEntity.ok("File uploaded successfully: " + fileName); } catch (IOException e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body("File upload failed: " + e.getMessage()); } } // 获取文件接口 @GetMapping("/{fileName}") public ResponseEntity<byte[]> getFile(@PathVariable String fileName) { try { Path filePath = Paths.get(uploadDir, fileName); byte[] fileContent = Files.readAllBytes(filePath); // 设置文件响应头 HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\""); headers.add(HttpHeaders.CONTENT_TYPE, Files.probeContentType(filePath)); return ResponseEntity.ok() .headers(headers) .body(fileContent); } catch (IOException e) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); } } }
创建 Spring Boot 的主类。
java 复制代码 package com.example.fileupload; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class FileUploadApplication { public static void main(String[] args) { SpringApplication.run(FileUploadApplication.class, args); } }
package com.example.fileupload; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class FileUploadApplication { public static void main(String[] args) { SpringApplication.run(FileUploadApplication.class, args); } }
请求:POST /api/files/upload参数: form-data 中 key 为 file,值为文件。
POST /api/files/upload
form-data
file
请求:GET /api/files/{fileName}将文件名作为路径参数。
GET /api/files/{fileName}
启动项目后,访问上传接口上传文件:
bash 复制代码 curl -F "file=@example.txt" http://localhost:8080/api/files/upload
curl -F "file=@example.txt" http://localhost:8080/api/files/upload
获取文件内容:
bash 复制代码 curl -O http://localhost:8080/api/files/example.txt
curl -O http://localhost:8080/api/files/example.txt
再次下载
iPhone浏览器用户: 1.点击手机桌面“文件”图标 2.在“下载”目录中查找