Springboot整合fastDfs管理使用文件笔记

一、安装搭建

请参考:centos系统安装搭建fastDFS

二、需要开放的端口

1、80(nginx)
2、22122(tracker)
3、23000(storage)

三、步骤

1、创建新Springboot项目,使用自己早期的hello-rabbit,导入核心依赖

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.2.RELEASE</version>
		<relativePath/> 
	</parent>
	
	<dependencies>
        <!--spring boot web的依赖-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!--fastdfs 客户端 依赖-->
		<dependency>
			<groupId>com.github.tobato</groupId>
			<artifactId>fastdfs-client</artifactId>
			<version>1.26.1-RELEASE</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		
	</dependencies>
	

2、给启动类添加的注解 @Import(FdfsClientConfig.class),代码如

package com.basic.hellorabbit;

import com.github.tobato.fastdfs.FdfsClientConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Import;
/**
* @Description:    项目启动类
* @Author:         Joe
* @CreateDate:     2020/3/20 14:15
*/
@Import(FdfsClientConfig.class)
@SpringBootApplication(scanBasePackages = "com.basic.hellorabbit")
public class HelloRabbitApplication {

	public static void main(String[] args) {
		SpringApplication.run(HelloRabbitApplication.class, args);
	}

}

3、给application.yml 加入fastDfs的配置,如图

fdfs:
  so-timeout: 1500  #socket连接超时时长
  connect-timeout: 600 #连接tracker服务器超时时长
  pool:
    jmx-enabled: false
  thumb-image: #缩略图生成参数,可选
    width: 150
    height: 150
  host: IP地址  #nginx访问地址
  port: 80              #nginx访问端口
  tracker-list: IP地址:22122

Springboot整合fastDfs管理使用文件笔记_第1张图片
4、fastDfs客户端工具类简单封装DfsClientUtil,DfsClientUtil.java如下

package com.basic.hellorabbit.util;

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

/**
* @Description:    客户端工具类
* @Author:         Joe
* @CreateDate:     2020/3/19 13:43
*/
@Component
public class DfsClientUtil {

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

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

    /**
     * 封装文件完整的URL
     * @param fullPath
     * @return
     */
    public String getCompleteURl(String fullPath){
        String fileUrl = "http://" + host + ":" + port + "/" + fullPath;
        return fileUrl;
    }

}

5、Controller接口(上传、下载、删除),DfsController.java

package com.basic.hellorabbit.controller;

import com.basic.hellorabbit.util.DfsClientUtil;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.proto.storage.DownloadCallback;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;


/**
* @Description:    fastDfs接口
* @Author:         Joe
* @CreateDate:     2020/3/19 13:02
*/
@Controller
public class DfsController {

    @Autowired
    private FastFileStorageClient fileStorageClient;

    @Autowired
    private DfsClientUtil dfsClientUtil;

    /**
     * 跳转到fastDfs测试页面
     * @return
     */
    @RequestMapping(value = "/dfs",method = RequestMethod.GET)
    public String toDfs(){
        return "dfs";
    }

    @ResponseBody
    @RequestMapping(value = "/dfsupload",method = RequestMethod.POST)
    public String upload(MultipartFile file) throws IOException {
        String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
        System.out.println("文件后缀名:"+suffixName);
        StorePath storePath = fileStorageClient.uploadFile(file.getInputStream(), file.getSize(), suffixName, null);
        String fullPath = storePath.getFullPath();
        if(!StringUtils.isEmpty(fullPath)){
            System.out.println("fullPath:"+fullPath);
            String completeURl = dfsClientUtil.getCompleteURl(fullPath);
            System.out.println("completeURl:"+completeURl);
            return "上传完成"+completeURl;
        }
        return "上传失败";

    }

    /**
     * 文件下载
     * @param filePath
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/download",method = RequestMethod.GET)
    public void download(String filePath, HttpServletRequest request , HttpServletResponse response) throws IOException {

        String[] paths = filePath.split("/");
        String groupName = null ;
        for (String item : paths) {
            if (item.indexOf("group1") != -1) {
                groupName = item;
                break ;
            }
        }
        String path = filePath.substring(filePath.indexOf(groupName) + groupName.length() + 1, filePath.length());
        InputStream inputStream = fileStorageClient.downloadFile(groupName, path, new DownloadCallback<InputStream>() {
            @Override
            public InputStream recv(InputStream inputStream) throws IOException {
                return inputStream;
            }
        });

        //根据文件名获取 MIME 类型
        String fileName = paths[paths.length-1] ;
        System.out.println("fileName :" + fileName);
        String contentType = request.getServletContext().getMimeType(fileName);
        String contentDisposition = "attachment;filename=" + fileName;

        // 设置头
        response.setHeader("Content-Type",contentType);
        response.setHeader("Content-Disposition",contentDisposition);

        // 获取绑定了客户端的流
        ServletOutputStream output = response.getOutputStream();

        // 把输入流中的数据写入到输出流中
        IOUtils.copy(inputStream,output);
        inputStream.close();
    }

    /**
     * 文件删除
     * @param filePath
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delfile",method = RequestMethod.GET)
    public String delfile(String filePath){
        String[] paths = filePath.split("/");
        String groupName = null ;
        for (String item : paths) {
            if (item.indexOf("group1") != -1) {
                groupName = item;
                break ;
            }
        }
        String path = filePath.substring(filePath.indexOf(groupName) + groupName.length() + 1, filePath.length());
        fileStorageClient.deleteFile(groupName,path);
        return "成功删除"+filePath;
    }
}

6、在resources/templates/新建dfs.html页面进行测试,dfs.html代码如下代码中IP自行替换即可

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>dfs测试页面</title>
</head>
<body>
<h3>文件上传</h3>
<br>
<hr/>
<form method="post" enctype="multipart/form-data" action="/dfsupload">
    <p>
        文件<input type="file" name="file"/>
    </p>
    <p>
        <input type="submit" value="开始上传"/>
    </p>
</form>
<hr/>
<br>
<br>
<h3>文件下载</h3>
<br>
<a href="/download?filePath=http://IP:80/group1/M00/00/00/rB8K-15zCxCAMJ6sABdNkG94T4U191.jpg">点击下载</a>
<hr/>
<br>
<br>
<h3>文件删除</h3>
<br>
<a href="/delfile?filePath=http://IP:80/group1/M00/00/00/rB8K-150hYeAU-joAAANv8mrNoM01.xlsx">点击删除</a>
</body>
</html>

希望看到的小伙伴多多指教,指导,指正

你可能感兴趣的:(常用代码块与笔记,spring,boot,fastdfs,java,封装,分布式)