1.首先在linux下安装好FastDFS, 安装步骤:https://www.cnblogs.com/handsomeye/p/9451568.html
2.引入FastDFS的依赖,在pom.xml引入:
<!--FastDFS客户端-->
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.26.1-RELEASE</version>
</dependency>
3.配置application.yml文件
server:
port: 8082
spring:
application:
name: upload-service
servlet:
multipart:
max-file-size: 100MB
fdfs:
so-timeout: 1501 # 读取超时时间
connect-timeout: 601 # 连接超时时间
thumb-image: # 缩略图
width: 60
height: 60
tracker-list: # tracker地址:你的虚拟机服务器地址+端口(默认是22122)
- 120.53.27.229:22122
4.将Fdfs配置引入项目
将FastDFS-Client客户端引入本地化项目的方式非常简单,在SpringBoot项目/src/[com.xxx.主目录]/conf当中配置
@Configuration
@Import(FdfsClientConfig.class)
// 解决jmx重复注册bean的问题
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class FastClientImporter {
}
5.将文件上传的工具类引入到service包下
@Service
public class UploadService {
private static final List<String> CONTENT_TYPES = Arrays.asList("image/gif","image/jpeg");
private static final Logger logger = LoggerFactory.getLogger(UploadService.class);
@Autowired
private FastFileStorageClient fastFileStorageClient;
public String uploadImage(MultipartFile file) {
String originalFilename = file.getOriginalFilename();
//校验文件类型
String contentType = file.getContentType();
if(!CONTENT_TYPES.contains(contentType)){
logger.info("文件类型不合法: {}",originalFilename);
return null;
}
try {
//校验文件内容
BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
if(bufferedImage == null){
logger.info("文件内容不合法: {}", originalFilename);
return null;
}
//保存到FastDfS服务器
String suffix = StringUtils.substringAfterLast(originalFilename, ".");
StorePath storePath = this.fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), suffix, null);
return "http://120.53.27.229/"+storePath.getFullPath();
} catch (IOException e) {
logger.info("服务器内部错误:" + originalFilename);
e.printStackTrace();
}
return null;
}
}
6.在controller包下写一个文件上传的方法
@Controller
@RequestMapping("upload")
public class UploadController {
@Autowired
private UploadService uploadService;
@PostMapping("image")
public String uploadImage(@RequestParam("file")MultipartFile file){
String url = this.uploadService.uploadImage(file);
if(StringUtils.isEmpty(url)){
// 请求参数不合法
System.out.println("请求参数不合法");
}
// 上传成功
System.out.println("图片路径:"+ url);
}
}