博主
258
258
258
258
专辑

第三节 SpringBoot集成FastDFS的文件上传

亮子 2021-07-23 08:17:11 6667 1 1 0

1、添加依赖

  • FastDFS 依赖

        <!-- FastDFS-->
        <dependency>
            <groupId>com.github.tobato</groupId>
            <artifactId>fastdfs-client</artifactId>
            <version>1.26.5</version>
        </dependency>
    

  • Swagger 依赖

        <!--    swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
            <exclusions>
                <exclusion>
                    <groupId>io.swagger</groupId>
                    <artifactId>swagger-models</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.swagger/swagger-models -->
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-models</artifactId>
            <version>1.5.22</version>
        </dependency>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.6</version>
        </dependency>

2、配置文件

# 修改文件上传大小限制
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

# 修改FastDFS设置
fdfs.connect-timeout=6000
fdfs.so-timeout=6000
fdfs.thumb-image.width=150
fdfs.thumb-image.height=150
fdfs.tracker-list=8.142.83.78:22122
# 通过nginx 访问地址
fdfs.resHost=8.142.83.78
fdfs.storagePort=8888
# 获取连接池最大数量
fdfs.pool.max-total=200
# 禁用jmx功能
spring.jmx.enabled=false

3、Swagger 配置类

package com.shenmazong.demofastdfs.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

/**
 * @author 军哥
 * @version 1.0
 * @description: Swagger 配置类
 * @date 2021/7/23 12:32
 */

@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.shenmazong.demofastdfs.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("SpringBoot利用Swagger构建API文档")
                .description("使用RestFul风格, 创建人:军哥")
                .termsOfServiceUrl("https://www.shenmazong.com")
                .version("version 1.0")
                .build();
    }
}

4、FastDFS配置类

package com.shenmazong.servertestdemo.config;

import com.github.tobato.fastdfs.FdfsClientConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.context.annotation.Import;
import org.springframework.jmx.support.RegistrationPolicy;

/**
 * @author 军哥
 * @version 1.0
 * @description: FastDFS配置类
 * @date 2022/1/16 22:29
 */

@Configuration
@Import(FdfsClientConfig.class)
@EnableMBeanExport(registration= RegistrationPolicy.IGNORE_EXISTING)
public class DfsConfig {
    @Value("${fdfs.resHost}")
    private String resHost;

    @Value("${fdfs.storagePort}")
    private String storagePort;

    public String getResHost() {
        return resHost;
    }

    public void setResHost(String resHost) {
        this.resHost = resHost;
    }

    public String getStoragePort() {
        return storagePort;
    }

    public void setStoragePort(String storagePort) {
        this.storagePort = storagePort;
    }
}

5、编写工具类

package com.shenmazong.servertestdemo.utils;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.Charset;

/**
 * @author 军哥
 * @version 1.0
 * @description: FastDFS上传文件工具类
 * @date 2022/1/16 22:35
 */


@Component
@Slf4j
public class FastFileUtil {


    @Autowired
    private FastFileStorageClient storageClient;

    private String serverUrl = "http://8.142.83.78:8888/";

    /**
     *	MultipartFile类型的文件上传ַ
     * @param file
     * @return
     * @throws IOException
     */
    public String uploadFile(MultipartFile file) throws IOException {
        StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(),
                FilenameUtils.getExtension(file.getOriginalFilename()), null);
        return getResAccessUrl(storePath);
    }

    /**
     * 普通的文件上传
     *
     * @param file
     * @return
     * @throws IOException
     */
    public String uploadFile(File file) throws IOException {
        FileInputStream inputStream = new FileInputStream(file);
        StorePath path = storageClient.uploadFile(inputStream, file.length(),
                FilenameUtils.getExtension(file.getName()), null);
        return getResAccessUrl(path);
    }

    /**
     * 带输入流形式的文件上传
     *
     * @param is
     * @param size
     * @param fileName
     * @return
     */
    public String uploadFileStream(InputStream is, long size, String fileName) {
        StorePath path = storageClient.uploadFile(is, size, fileName, null);
        return getResAccessUrl(path);
    }

    /**
     * 将一段文本文件写到fastdfs的服务器上
     *
     * @param content
     * @param fileExtension
     * @return
     */
    public String uploadFile(String content, String fileExtension) {
        byte[] buff = content.getBytes(Charset.forName("UTF-8"));
        ByteArrayInputStream stream = new ByteArrayInputStream(buff);
        StorePath path = storageClient.uploadFile(stream, buff.length, fileExtension, null);
        return getResAccessUrl(path);
    }

    /**
     * 返回文件上传成功后的地址名称ַ
     * @param storePath
     * @return
     */
    private String getResAccessUrl(StorePath storePath) {
        String fileUrl = serverUrl + storePath.getFullPath();
        return fileUrl;
    }

    /**
     * 删除文件
     * @param fileUrl
     */
    public void deleteFile(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            return;
        }
        try {
            StorePath storePath = StorePath.parseFromUrl(fileUrl);
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (FdfsUnsupportStorePathException e) {
            log.warn(e.getMessage());
        }
    }

//    public String upfileImage(InputStream is, long size, String fileExtName, Set<MateData> metaData) {
//        StorePath path = storageClient.uploadImageAndCrtThumbImage(is, size, fileExtName, metaData);
//        return getResAccessUrl(path);
//    }

}

6、controller接口类

package com.shenmazong.user.controller;

import com.shenmazong.user.utils.FastFileUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author 军哥
 * @version 1.0
 * @description: FastDFS文件上传接口
 * @date 2022/6/24 20:31
 */

@Api(tags = "FastDFS文件上传")
@RestController
@Slf4j
@RequestMapping(value = "/fast")
public class FastDfsController {

    @Autowired
    FastFileUtil fastFileUtil;

    @PostMapping(value = "/upload")
    public String upload(@RequestParam("file") MultipartFile multipartFile) throws IOException {

        String url = fastFileUtil.uploadFile(multipartFile);
        log.warn(url);
        return url;
    }

}

7、启动项目并测试

测试地址:

图片alt

返回地址表示上传成功。

9、回显地址

默认的话,是通过你的 ip:8888/上面返回的地址 如果你是阿里云服务就要手动开放 8888、22122、23000 这三个端口

例如:

http://8.131.235.152:8888/group1/M00/00/00/rByEyGD6cJCAFTAYAABwmRC_p9w457.png

图片alt

参考文章