1、创建SpringBoot项目
2、修改pom.xml
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.26.7</version>
</dependency>
3、创建配置类UploadProperties
package com.coydone.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.List;
@ConfigurationProperties(prefix = "upload")
public class UploadProperties {
private String baseUrl;
private List<String> allowTypes;
public String getBaseUrl() {
return baseUrl;
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
public List<String> getAllowTypes() {
return allowTypes;
}
public void setAllowTypes(List<String> allowTypes) {
this.allowTypes = allowTypes;
}
}
4、配置yaml
fdfs:
so-timeout: 2500 # 读取时间
connect-timeout: 600 # 连接超时时间
thumb-image: # 缩略图
100
height: 100
tracker-list: # tracker服务配置地址列表
- 116.62.44.5:22122
upload:
base-url: http://116.62.44.5/
allow-types:
- image/jpeg
- image/png
- image/bmp
- image/gif
5、创建UploadService
@Component
@EnableConfigurationProperties(UploadProperties.class)
public class UploadService {
private Log log= LogFactory.getLog(UploadService.class);
@Autowired
private FastFileStorageClient storageClient;
@Autowired
private UploadProperties prop;
public String uploadImage(MultipartFile file) {
// 1、校验文件类型
String contentType = file.getContentType();
if (!prop.getAllowTypes().contains(contentType)) {
throw new RuntimeException("文件类型不支持");
}
// 2、校验文件内容
try {
BufferedImage image = ImageIO.read(file.getInputStream());
if (image == null || image.getWidth() == 0 || image.getHeight() == 0) {
throw new RuntimeException("上传文件有问题");
}
} catch (IOException e) {
log.error("校验文件内容失败....{}", e);
throw new RuntimeException("校验文件内容失败"+e.getMessage());
}
try {
// 3、上传到FastDFS
// 3.1、获取扩展名
String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
// 3.2、上传
StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);
// 返回路径
return prop.getBaseUrl() + storePath.getFullPath();
} catch (IOException e) {
log.error("【文件上传】上传文件失败!....{}", e);
throw new RuntimeException("【文件上传】上传文件失败!"+e.getMessage());
}
}
}
6、创建UploadController
@RestController
@RequestMapping("upload")
public class UploadController {
@Autowired
private UploadService uploadService;
//上传
@RequestMapping("doUpload")
public Map<String,Object> doUpload(MultipartFile mf){
System.out.println(mf.getOriginalFilename());
Map<String, Object> map = uploadService.upload(mf);
return map;
}
}
7、创建static/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>文件上传</h1>
<hr>
<form action="/upload/doUpload" method="post" enctype="multipart/form-data">
<input type="file" name="mf">
<input type="submit" value="上传">
</form>
</body>
</html>
8、测试
运行项目,浏览器访问http://localhost:8080/upload/doUpload