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: # 縮略圖
width: 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