用Spring Boot文件上传写一个实现只能上传图片代码
时间: 2024-01-29 17:02:00 浏览: 38
好的,以下是用 Spring Boot 实现只能上传图片的代码示例:
首先需要添加依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
```
然后在控制器中定义上传图片的接口,只允许上传图片类型的文件:
```
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
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.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;
@RestController
public class FileController {
@PostMapping("/uploadImage")
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
String fileName = file.getOriginalFilename();
// 验证是否为图片类型
String extension = FilenameUtils.getExtension(fileName);
if (StringUtils.isBlank(extension) || !extension.matches("^(jpg|jpeg|png|gif)$")) {
return "上传失败,请上传图片文件!";
}
// 生成新的文件名
String newFileName = UUID.randomUUID().toString() + "." + extension;
// 拼接文件路径
File uploadPath;
try {
uploadPath = new File(ResourceUtils.getURL("classpath:").getPath());
if (!uploadPath.exists()) {
uploadPath = new File("");
}
File imgPath = new File(uploadPath.getAbsolutePath(), "/static/upload/img/");
if (!imgPath.exists()) {
imgPath.mkdirs();
}
File dest = new File(imgPath, newFileName);
file.transferTo(dest);
return "/upload/img/" + newFileName;
} catch (FileNotFoundException e) {
e.printStackTrace();
return "上传失败," + e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "上传失败," + e.getMessage();
}
}
}
```
上面的代码中,首先根据上传的文件名判断是否为图片类型,然后生成新的文件名,将文件保存到指定的路径中,最后返回保存后的文件路径。
请注意,在使用这段代码时,需要在 Spring Boot 项目的 resources 目录下创建 static/upload/img 目录,用于存储上传的图片文件。