使用Spring Boot实现图片上传和展示
以下是一个使用Spring Boot实现图片上传和展示的简单示例。
首先,添加依赖到你的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>
然后,创建一个控制器来处理上传和展示:
import org.springframework.stereotype.Controller;
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.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
@Controller
public class ImageUploadController {
private static final String UPLOAD_DIR = "uploads/";
@GetMapping("/")
public String index() {
return "upload";
}
@PostMapping("/upload")
public String uploadImage(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "Upload failed!";
}
try {
String filename = file.getOriginalFilename();
File destFile = new File(UPLOAD_DIR + filename);
if (!destFile.exists()) {
destFile.mkdirs();
}
file.transferTo(Paths.get(UPLOAD_DIR + filename));
return "redirect:/image?filename=" + filename;
} catch (IOException e) {
e.printStackTrace();
return "Upload failed!";
}
}
@GetMapping("/image")
@ResponseBody
public byte[] getImage(@RequestParam(value = "filename") String filename) throws IOException {
File file = new File(UPLOAD_DIR + filename);
return org.apache.commons.io.FileUtils.readFileToByteArray(file);
}
}
在src/main/resources/templates
目录下创建upload.html
文件:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Image Upload</title>
</head>
<body>
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload" />
</form>
</body>
</html>
在src/main/resources/application.properties
文件中配置上传目录:
spring.servlet.multipart.location=/temp
确保UPLOAD_DIR
评论已关闭