1. pom文件中引入相应的依赖
<!--fastdfs操作包-->
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
</dependency>
2. 配置yml文件
fdfs:
so-timeout: 2500 # 读取时间
connect-timeout: 600 # 连接超时时间
thumb-image: # 缩略图
width: 100
height: 100
tracker-list: # tracker服务配置地址列表
- 127.0.0.1:22122
upload:
base-url: http://127.0.0.1:8888
allow-types:
- image/jpg
- image/jpeg
- image/png
- image/bmp
3.编写文件上传属性
/**
* @Description 文件上传属性
* @Author
*/
@ConfigurationProperties(prefix = "upload")
@Data
public class UploadProperties {
private String baseUrl;
private List<String> allowTypes;
}
4. 编写上传服务
/**
* @Description 文件上传服务
* @Author
*/
@Service
@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());
}
}
/**
* 删除图片 相对路径
* @param path
* @return
*/
public void deleteFile(String path) {
if(StringUtils.isNotBlank(path)){
try {
//删除
storageClient.deleteFile(path);
log.info("【文件删除】文件删除成功!...."+path);
} catch (Exception e) {
log.error("【文件删除】文件删除失败!....{}", e);
throw new RuntimeException("【文件上传】上传文件失败!"+e.getMessage());
}
}
}
}
5.编写controller进行接收参数
@Autowired
private UploadService uploadService;
/**
* 文件图片 ---检查结果
*/
@PostMapping("doUploadImage")
public AjaxResult uploadFile(MultipartFile mf){
Map<String,Object> map=new HashMap<>();
if(null!=mf){
map.put("name",mf.getOriginalFilename());
String path = this.uploadService.uploadImage(mf);
map.put("url",path);
System.out.println(map);
return AjaxResult.success(map);
}else{
return AjaxResult.error("上传文件失败");
}
}
好,结束