springboot项目搭建(八)--使用Spring Boot集成FastDFS

1、建立一个springboot的工程,下面的是我的目录结构:

springboot项目搭建(八)--使用Spring Boot集成FastDFS_第1张图片

2、pom文件引入依赖:

 
        UTF-8
        UTF-8
        1.8
        3.3.2
    

    

        
            org.springframework.boot
            spring-boot-starter
        

        
            org.projectlombok
            lombok
            true
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
        
            org.springframework.boot
            spring-boot-configuration-processor
            true
        

        
            org.springframework.boot
            spring-boot-starter-freemarker
        

        
            org.springframework.boot
            spring-boot-starter-amqp
        

        
            org.springframework.boot
            spring-boot-starter-data-redis
            
            
                
                    redis.clients
                    jedis
                
                
                    io.lettuce
                    lettuce-core
                
            
        

        
            org.springframework.boot
            spring-boot-starter-redis
            1.4.1.RELEASE
        

        
        
            redis.clients
            jedis
        

        
        
            com.oracle
            ojdbc6
            11.2.0.3
        

        
        
            com.github.pagehelper
            pagehelper
            5.1.4
        

        
        
            org.apache.commons
            commons-lang3
            ${commons-lang3.version}
        

        
        
        
            org.apache.commons
            commons-pool2
            2.5.0
        

        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.3.2
        

        
            org.springframework.boot
            spring-boot-devtools
            runtime
        

        
            mysql
            mysql-connector-java
            runtime
        

        
        
            com.alibaba
            druid-spring-boot-starter
            1.1.9
        

        
        
            com.alibaba
            fastjson
            1.2.47
        

        
        
            io.springfox
            springfox-swagger2
            2.7.0
        

        
            io.springfox
            springfox-swagger-ui
            2.7.0
        

        
        
            com.github.tobato
            fastdfs-client
            1.26.1-RELEASE
        

        
            commons-io
            commons-io
            2.4
        

        
            commons-codec
            commons-codec
            1.9
        

        
            org.springframework
            spring-jdbc
            4.3.13.RELEASE
        

        
            com.zaxxer
            HikariCP
            3.2.0
        

        
            org.springframework.boot
            spring-boot-starter-quartz
        

        
            org.springframework.boot
            spring-boot-starter-aop
        

        
            commons-beanutils
            commons-beanutils-core
            1.8.3
        

    

这个是方便在yml中自定义参数听过@Value的形式注入

springboot项目搭建(八)--使用Spring Boot集成FastDFS_第2张图片

这个依赖确保是1.26.1以上的不然SpringBoot2.0集成会报错

springboot项目搭建(八)--使用Spring Boot集成FastDFS_第3张图片

 

按照截图创建包以及建立类:

springboot项目搭建(八)--使用Spring Boot集成FastDFS_第4张图片

3、编写FdfsConfig 类

package com.saliai.logsystem.common.conf;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author: Martin
 * @Date: 2018/10/12
 * @Description:
 * @Modify By:
 */
@Component
public class FdfsConfig {
    @Value("${fdfs.res-host}")
    private String resHost;

    @Value("${fdfs.storage-port}")
    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;
    }

}

4、编写 FdfsConfiguration 类

package com.saliai.logsystem.common.conf;

/**
 * @author: Martin
 * @Date: 2018/10/12
 * @Description:
 * @Modify By:
 */

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)
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class FdfsConfiguration {
}

 

5、建立constants包并建立GlobalConstants类

 

package com.saliai.logsystem.common.constants;

/**
 * @author: Martin
 * @Date: 2018/10/25
 * @Description:
 * @Modify By:
 */
public class GlobalConstants {
    public final static String HTTP_FILEURL = "http://baihoomall.100healths.cn";
}

 

6、创建截图中的FastDFSClientWrapper类:

package com.saliai.logsystem.common.utils;

/**
 * @author: Martin
 * @Date: 2018/9/28
 * @Description:
 * @Modify By:
 */

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.saliai.logsystem.common.conf.FdfsConfig;
import com.saliai.logsystem.common.constants.GlobalConstants;
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.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 功能描述: 文件处理类
 *
 * @author Martin
 * @version V1.0
 * @date 2018/10/12
 */
@Component
@Slf4j
public class FastDFSClientWrapper {

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private FdfsConfig fdfsConfig;

    public String uploadFile(MultipartFile file) throws IOException {
        StorePath storePath = storageClient.uploadFile((InputStream) file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
        log.info("storePath:" + storePath);
        return getResAccessUrl(storePath);
    }

    /**
     * 封装文件完整URL地址
     *
     * @param storePath
     * @return
     */
    private String getResAccessUrl(StorePath storePath) {
        //GlobalConstants.HTTP_PRODOCOL +
        String fileUrl = GlobalConstants.HTTP_FILEURL + ":" + fdfsConfig.getStoragePort() + "/" + storePath.getFullPath();
        log.info("fileUrl:" + fileUrl);
        return fileUrl;
    }

    /**
     * 功能描述: 删除文件
     *
     * @param fileUrl
     * @return void
     * @author Martin
     * @date 2018/10/12
     * @version V1.0
     */
    public void deleteFile(String fileUrl) {

        log.info("删除的文件的url:" + fileUrl);
        if (StringUtils.isEmpty(fileUrl)) {
            return;
        }
        try {
            StorePath storePath = StorePath.praseFromUrl(fileUrl);
            log.info("groupName:"+storePath.getGroup()+"------"+"文件路径path:"+storePath.getPath());
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (FdfsUnsupportStorePathException e) {
            log.warn(e.getMessage());
        }
    }

    /**
     * 功能描述: 下载文件
     *
     * @param fileUrl
     * @return java.io.InputStream
     * @author Martin
     * @date 2018/10/12
     * @version V1.0
     */
    public InputStream downFile(String fileUrl) {
        try {
            StorePath storePath = StorePath.praseFromUrl(fileUrl);
            byte[] fileByte = storageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadByteArray());
            InputStream ins = new ByteArrayInputStream(fileByte);
            return ins;
        } catch (Exception e) {
            log.error("Non IO Exception: Get File from Fast DFS failed", e);
        }
        return null;
    }
}

7、接下来编写controller进行测试

package com.saliai.logsystem.controller;

import com.saliai.logsystem.common.utils.FastDFSClientWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;

/**
 * @author: Martin
 * @Date: 2018/9/28
 * @Description:
 * @Modify By:
 */
@Controller
@RequestMapping("/upload")
public class UploadController {
    @Autowired
    private FastDFSClientWrapper dfsClient;

    @GetMapping("/")
    public String index() {
        return "upload/upload";
    }

    @PostMapping("/fdfs_upload")
    public String fdfsUpload(@RequestParam("file") MultipartFile file,
                             RedirectAttributes redirectAttributes) {
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
            return "redirect:/upload/uploadStatus";
        }

        try {
            String fileUrl = dfsClient.uploadFile(file);
            redirectAttributes.addFlashAttribute("message",
                    "You successfully uploaded '" + fileUrl + "'");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:/upload/uploadStatus";
    }

    @GetMapping("/uploadStatus")
    public String uploadStatus() {
        return "upload/uploadStatus";
    }

    @RequestMapping("/deleteFile")
    @ResponseBody
    public String deleteFile(@RequestParam(value = "fileUrl") String fileUrl) {
        dfsClient.deleteFile(fileUrl);
        return "Success";
    }
}

8、建立页面测试上传功能。这里使用freemarker

springboot项目搭建(八)--使用Spring Boot集成FastDFS_第5张图片

 

upload.ftl:









Spring Boot file upload example



 

uploadStatus.ftl:









Spring Boot - Upload Status

${message}

 

在启动类中加上@EnableAutoConfiguration注解

springboot项目搭建(八)--使用Spring Boot集成FastDFS_第6张图片

 

在配置文件中加入这两个截图的东西:

 

springboot项目搭建(八)--使用Spring Boot集成FastDFS_第7张图片

9、启动项目,进行测试

springboot项目搭建(八)--使用Spring Boot集成FastDFS_第8张图片

springboot项目搭建(八)--使用Spring Boot集成FastDFS_第9张图片

 

提交,进行文件上传:

springboot项目搭建(八)--使用Spring Boot集成FastDFS_第10张图片

返回文件的地址,直接拷贝到浏览器访问,看看是否能访问。

springboot项目搭建(八)--使用Spring Boot集成FastDFS_第11张图片

这样就完成了文件上传的步骤。

最后附上代码https://download.csdn.net/download/qq_756589808/10745609

你可能感兴趣的:(Spring,Boot)