使用Spring Boot和Spring MVC实现图片上传到服务器。
1. 引入依赖
在你的pom.xml
文件中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2. 创建Spring Boot应用程序主类
Application.java
:
package com.example.upload;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
3. 创建文件上传控制器
FileUploadController.java
:
package com.example.upload.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
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;
@Controller
public class FileUploadController {
// 指定文件上传路径
private static String UPLOADED_FOLDER = "uploads/";
@GetMapping("/")
public String index() {
return "upload";
}
@PostMapping("/upload")
public String singleFileUpload(@RequestParam("file") MultipartFile file, Model model) {
if (file.isEmpty()) {
model.addAttribute("message", "Please select a file to upload");
return "upload";
}
try {
// 获取文件并保存到指定路径
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);
model.addAttribute("message", "You successfully uploaded '" + file.getOriginalFilename() + "'");
} catch (IOException e) {
e.printStackTrace();
}
return "upload";
}
}
4. 创建上传页面
在src/main/resources/templates
目录下创建upload.html
:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>File Upload</title>
</head>
<body>
<h2>Upload a file</h2>
<form method="POST" enctype="multipart/form-data" action="/upload">
<input type="file" name="file"/>
<button type="submit">Upload</button>
</form>
<p th:if="${message}" th:text="${message}"></p>
</body>
</html>
5. 创建文件上传目录
确保在项目的根目录下创建一个名为uploads
的文件夹,用于保存上传的文件。
6. 配置文件上传大小限制(可选)
在src/main/resources/application.properties
中,可以配置文件上传的大小限制:
spring.servlet.multipart.max-file-size=2MB
spring.servlet.multipart.max-request-size=2MB
7. 运行应用程序
运行Application
类,启动Spring Boot应用程序。然后在浏览器中访问http://localhost:8080
,看到文件上传页面。选择一个文件并点击上传按钮,文件将被上传并保存到服务器的uploads
文件夹中。上传的文件会保存到服务器指定的目录中,同时页面会显示上传成功的信息。