一、准备工作
请确保fastDFS的tracker服务和storage服务都是处于启动状态,防火墙是关闭的;
二、具体步骤
1、pom.xml
2、让当前的微服务成为fdfs的客户端
package com.qf.config;import com.github.tobato.fastdfs.FdfsClientConfig;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.context.annotation.Import;
import org.springframework.jmx.support.RegistrationPolicy;/*** ClassName: FastClientImporter** @author Guan* Description : 管理fdfs的客户端* date: 2024/2/3 18:55*/
@Configuration
@Import(FdfsClientConfig.class)//引入客户端的配置类
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)//避免重复注册bean
public class FastClientImporter {
}
3、设置文件上传
package com.qf.controller;import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.qf.utils.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;/*** ClassName: FileUploadController** @author Guan* Description : 用于文件上传(主要是图片)* date: 2024/2/3 18:58*/
@RestController
@RequestMapping("file")
public class FileUploadController {@Autowiredprivate FastFileStorageClient storageClient;//定义上传的文件的后缀private static final List<String> CONTENT_TYPES = Arrays.asList("image/jpg","image/jpeg","image/png","image/gif");@PostMapping("upload")public Result fileUpload(MultipartFile file){try {String originalFilename = file.getOriginalFilename();// 校验文件的类型String contentType = file.getContentType();if (!CONTENT_TYPES.contains(contentType)){// 文件类型不合法,直接返回return Result.error("文件类型不合法:"+originalFilename);}// 校验文件的内容BufferedImage bufferedImage = ImageIO.read(file.getInputStream());if (bufferedImage == null) {return Result.error("文件内容不合法:" + originalFilename);}// 保存到服务器String ext = StringUtils.substringAfterLast(originalFilename, ".");StorePath storePath = this.storageClient.uploadFile(file.getInputStream(),file.getSize(), ext, null);// 生成url地址,返回return Result.ok("http://image.shop.com/" + storePath.getFullPath());} catch (IOException e) {e.printStackTrace();}return Result.error("服务器内部错误");}
}
注意:域名image.shop.com是我自己搭的域名,依靠nginx,用来代理fdfs服务的;