欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

FastDFS(5):在SpringBoot测试上传文件到FastDFS(推荐)

程序员文章站 2022-06-03 08:56:38
...

1、首先新建一个SpringBoot Maven 项目

pom 依赖如下

<!-- https://mvnrepository.com/artifact/com.github.tobato/fastdfs-client -->
<dependency>
    <groupId>com.github.tobato</groupId>
    <artifactId>fastdfs-client</artifactId>
    <version>1.26.7</version>
</dependency>

2、配置相关规则

/**
 * @ConfigurationProperties:用于读取yml文件或properties文件的值
 *  其他类可以通过@EnableConfigurationProperties直接加载
 *
 * @author wcong
 * @version 1.0
 * @date 2020-05-06 13:53
 */
@Data
@ConfigurationProperties(prefix = "upload")
@Component
public class UploadProperties {

    private String baseUrl;

    private List<String> allowTypes;

}

3、yml 文件

fdfs:
  so-timeout: 2500       # 读取时间
  connect-timeout: 600   # 连接超时时间
  thumb-image:           # 缩略图
    width: 100
    height: 100
  tracker-list:          # tracker 服务地址,可配置多个
    - 391.106.941.239:22122

upload:
  base-url: http://391.106.941.239:900/
  allow-types:          # miniTypes参考:https://www.w3school.com.cn/media/media_mimeref.asp
    - image/jpeg
    - image/png
    - image/bmp
    - image/gif

4、UploadService

/**
 * @author wcong
 * @version 1.0
 * @date 2020-05-06 14:15
 */
@Service
@Slf4j
@EnableConfigurationProperties(UploadProperties.class)
public class UploadService {


    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private UploadProperties uploadProperties;

    public String uploadImage(MultipartFile file) {
        // 1、校验文件类型
        String contentType = file.getContentType();
        if (!uploadProperties.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 uploadProperties.getBaseUrl() + storePath.getFullPath();
        } catch (IOException e) {
            log.error("【文件上传】上传文件失败!....{}", e);
            throw  new RuntimeException("【文件上传】上传文件失败!"+e.getMessage());
        }
    }
}

5、UploadController

/**
 * @author wcong
 * @version 1.0
 * @date 2020-05-06 14:27
 */
@RestController
@RequestMapping("upload")
public class UpoadController {

    @Autowired
    private UploadService uploadService;

    @PostMapping("/doUpload")
    public Map<String,Object> doUpload(MultipartFile file){
        Map<String,Object> map = new HashMap<>();
        String filePath = uploadService.uploadImage(file);
        map.put("path",filePath);
        return map;
    }

}

6、index.html 测试

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件图片到fastDFS服务器</title>
</head>
<body>
    <h1>上传图片</h1>

    <form action="/upload/doUpload" method="post" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" value="上传">
    </form>

</body>
</html>

7、查看测试结果

FastDFS(5):在SpringBoot测试上传文件到FastDFS(推荐)
返回值:
FastDFS(5):在SpringBoot测试上传文件到FastDFS(推荐)
点击链接即可查看上传的图片
FastDFS(5):在SpringBoot测试上传文件到FastDFS(推荐)

相关标签: FastDFS