SpringCloud使用FastDFS
上传文件微服务模块结构
配置文件
-
pom.xml----->引入fastdfs依赖(在父工程下引入了版本信息, 所以在该微服务下, 不用引入版本信息)
<dependency> <groupId>com.github.tobato</groupId> <artifactId>fastdfs-client</artifactId> <version>1.26.1-RELEASE<ersion> </dependency>
-
pom.xml----->该上传文件微服务全部依赖
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>leyou</artifactId> <groupId>com.leyou.parent</groupId> <version>1.0.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <groupId>com.leyou.service</groupId> <artifactId>ly-upload</artifactId> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <!-- 引入fastdfs客户端 --> <dependency> <groupId>com.github.tobato</groupId> <artifactId>fastdfs-client</artifactId> </dependency> <!-- 引用test启动器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <dependency> <groupId>com.leyou.common</groupId> <artifactId>ly-common</artifactId> <version>1.0.0-SNAPSHOT</version> </dependency> </dependencies> </project>
-
application.yml----->配置fastdfs
fdfs: # 请求超时时间 so-timeout: 1501 # 连接超时时间 connect-timeout: 601 thumb-image: # 缩略图, (可以自由配置, 这里只是为了加载快) width: 60 height: 60 tracker-list: # tracker地址 - 192.168.79.128:22122
-
application.yml----->该上传文件微服务全部配置
server: port: 8083 spring: application: name: upload-service servlet: multipart: max-file-size: 5MB # 限制文件上传的大小 # Eureka eureka: client: service-url: defaultZone: http://127.0.0.1:10086/eureka instance: lease-renewal-interval-in-seconds: 5 # 每隔5秒发送一次心跳 lease-expiration-duration-in-seconds: 10 # 10秒不发送就过期 prefer-ip-address: true ip-address: 127.0.0.1 instance-id: ${spring.application.name}:${server.port} fdfs: # 请求超时时间 so-timeout: 1501 # 连接超时时间 connect-timeout: 601 thumb-image: # 缩略图, (可以自由配置, 这里只是为了加载快) width: 60 height: 60 tracker-list: # tracker地址 - 192.168.79.128:22122 # 配置文件上传的域名 ly: upload: baseUrl: http://image.leyou.com/ allowTypes: - image/jpeg - image/png
启动类
-
UploadApplication
package com.leyou.upload; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; /** * @program: leyou * @description: * @author: Mr.Xiao * @create: 2020-05-27 19:04 **/ @SpringBootApplication @EnableDiscoveryClient public class UploadApplication { public static void main(String[] args) { SpringApplication.run(UploadApplication.class); } }
Config
-
FastClientImporter------>fastdfs客户端
package com.leyou.upload.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; @Configuration @Import(FdfsClientConfig.class) // 解决jmx重复注册bean的问题 @EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING) public class FastClientImporter { }
-
UploadProperties------->java配置类
package com.leyou.upload.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import java.util.List; /** * @program: leyou * @description: * @author: Mr.Xiao * @create: 2020-05-28 18:07 **/ @Data @Component @ConfigurationProperties(prefix = "ly.upload") public class UploadProperties { private String baseUrl; private List<String> allowTypes; }
Controller
-
UploadController
package com.leyou.upload.web; import com.leyou.common.enums.ExceptionEnum; import com.leyou.common.exception.LyException; import com.leyou.upload.service.UploadService; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; /** * @program: leyou * @description: * @author: Mr.Xiao * @create: 2020-05-28 09:31 **/ @RestController @RequestMapping("/upload") public class UploadController { @Autowired private UploadService uploadService; @PostMapping("/image") public ResponseEntity<String> uploadImage (@RequestParam("file") MultipartFile file) { String url = uploadService.uploadImage(file); if (StringUtils.isBlank(url)) { throw new LyException(ExceptionEnum.INVALID_FILE_TYPE); } return ResponseEntity.status(HttpStatus.CREATED).body(url); } }
Service
-
UploadService接口
package com.leyou.upload.service; import org.springframework.web.multipart.MultipartFile; /** * @program: leyou * @description: 表现层上传文件 * @author: Mr.Xiao * @create: 2020-05-28 09:53 **/ public interface UploadService { /** * 上传图片 * @param file * @return */ String uploadImage(MultipartFile file); }
-
UploadServiceImpl实体类
package com.leyou.upload.service.impl; import com.github.tobato.fastdfs.domain.StorePath; import com.github.tobato.fastdfs.service.FastFileStorageClient; import com.leyou.upload.config.UploadProperties; import com.leyou.common.enums.ExceptionEnum; import com.leyou.common.exception.LyException; import com.leyou.upload.service.UploadService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.IOException; /** * @program: leyou * @description: 业务层 上传图片实现类 * @author: Mr.Xiao * @create: 2020-05-28 09:54 **/ @Service("uploadService") @Slf4j @EnableConfigurationProperties(UploadProperties.class) // 引入配置类 public class UploadServiceImpl implements UploadService { @Autowired // 注入fastdfs上传文件bean private FastFileStorageClient fastFileStorageClient; @Autowired private UploadProperties uploadProperties; /** * 上传图片 * @param file * @return */ @Override public String uploadImage(MultipartFile file) { try { // 校验文件 String type = file.getContentType(); // 判断文件是否在这个类型里面 if (!uploadProperties.getAllowTypes().contains(type)) { throw new LyException(ExceptionEnum.INVALID_FILE_TYPE); } // 校验内容 BufferedImage imageContent = ImageIO.read(file.getInputStream()); // 为null不是图片 if (imageContent == null) { throw new LyException(ExceptionEnum.INVALID_FILE_TYPE); } // 将文件上传到FastDFS // 获取文件后缀 String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), "."); /* 第一个参数: 上传文件流 第二个参数: 文件大小 第三个参数: 文件后缀 第四个参数: set集合, 可以直接用null */ StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null); // 返回路径 , 带group的 return uploadProperties.getBaseUrl() + storePath.getFullPath(); } catch (IOException e) { // 上传失败 log.error("[文件上传] 上传文件失败!", e); throw new LyException(ExceptionEnum.UPLOAD_FILE_ERROR); } } }