检查依赖
确保pom.xml包含了Spring Boot Web的依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId>
</dependency>
创建Controller
创建公用上传文件控制器
package com.example.ruijisboot.common;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;@RestController
public class FileUploadController {@Autowiredprivate ServletContext servletContext;@PostMapping("/upload")public R handleFileUpload(MultipartFile file) {System.out.println(file);if (file.isEmpty()) {
// return "Please select a file to upload.";return R.error("Please select a file to upload.");}try {// 构建上传目录的路径String uploadDir = servletContext.getRealPath("/upload/test/");// 确保目录存在File dirPath = new File(uploadDir);if (!dirPath.exists()) {dirPath.mkdirs();}// 构建上传文件的完整路径Path path = Paths.get(uploadDir).resolve(file.getOriginalFilename());System.out.println(path);// 保存文件Files.write(path, file.getBytes());// 构建文件在Web应用中的URLString fileUrl = ServletUriComponentsBuilder.fromCurrentContextPath().path("/upload/test/").path(file.getOriginalFilename()).toUriString();
// return "File uploaded successfully! You can download it from: " + fileUrl;return R.success(fileUrl,"成功");} catch (IOException e) {e.printStackTrace();
// return "File upload failed!";return R.error("File upload failed!");}}
}
这里R为我本地封装的统一返回格式的类
配置属性
在application.properties或application.yml中,你可以配置一些与文件上传相关的属性,比如文件大小限制等。
# application.properties 示例
spring.servlet.multipart.max-file-size=128KB
spring.servlet.multipart.max-request-size=10MB
验证
请求 /upload
路径
文件会默认放在系统的临时文件目录