在fastDFS已配置好的情况下,关于图片上传的业务代码
1.首先在pom文件中导入相关依赖
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.26.1-RELEASE</version>
</dependency>
2.之后需要在application.yml文件中配置
fdfs:
tracker-list:
-192.168.1.6:22122 #tracker服务的地址 可以配置多个trackerserver
so-timeout: 3000 #读取文件超时时间
connect-timeout: 3000 #连接超时时间
thumb-image: #缩略图
height: 200
width: 200
fasthome:http://192.168.1.6:8080/
3.然后需要在主启动类上增加两个注解
//FastDFS的两个注解需要配置
@Import(FdfsClientConfig.class)
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
4.最后就是Controller层的相关代码
package com.baisui.controller;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
/**
* @Author: baiLu
* @Date: 2021/09/14/15:54
* @Description:
*/
@Controller
@RequestMapping("/ruController")
public class ResourcesUploadController {
@Autowired
private FastFileStorageClient fastFileStorageClient;
//application.yml文件中配置的地址
@Value("${fasthome}")
private String dfsHome;
@RequestMapping("/uploadPng")
public String uploadPng(MultipartFile file){
//把一个文件上传到FastDFS上
try{
//获取文件后缀名
String fileExtname = FilenameUtils.getExtension(file.getOriginalFilename());
StorePath StorePath = fastFileStorageClient.uploadImageAndCrtThumbImage(file.getInputStream(),file.getSize(),fileExtname,null);
//获取文件上传的路径
String fullPath = StorePath.getFullPath();
//把路径返回给客户端
return dfsHome+fullPath;
}catch (IOException e){
e.printStackTrace();
}
return "ok";
}
}
5.打完收工!