
首先,确保你的Spring Boot项目中已经包含了`spring-boot-starter-web`依赖,它提供了处理HTTP请求和响应所需的基础功能。
接下来,我们需要创建一个控制器来处理文件上传请求。以下是一个简单的控制器示例:
java
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;
@RestController
@RequestMapping("/upload")
public class FileUploadController {
@PostMapping("/image")
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
String fileName = UUID.randomUUID().toString() + file.getOriginalFilename();
String filePath = "static/images/" + fileName;
try {
// 将文件保存到指定的路径
File newFile = new File(filePath);
file.transferTo(newFile);
// 返回成功信息
return "File uploaded successfully!";
} catch (IOException e) {
// 处理文件上传异常
e.printStackTrace();
return "Error uploading file!";
}
}
}
在这个控制器中,我们定义了一个`handleFileUpload`方法,它接受一个`MultipartFile`类型的参数,这是Spring MVC提供的用于处理多部分请求体的接口。我们使用`UUID`生成一个唯一的文件名,并将文件保存到`static/images/`目录下。
确保在`application.properties`或`application.yml`文件中配置了静态资源的路径:
properties
# application.properties
spring.mvc.static-path-pattern=/static/**
或者
yaml
# application.yml
spring:
mvc:
static-path-pattern: /static/**
这样配置后,Spring Boot会识别`/static`路径下的资源,并将其映射到`src/main/resources/static`目录下。
最后,在前端页面上,你可以使用`
转载请注明出处:https://www.wanxiangsucai.com/read/cv183920