springboot集成fastDFS实现文件上传

1、安装虚拟机,镜像,在linux系统中安装好fastDFS并启动

2、代码实现

目录结构
在这里插入图片描述
主要结构控制层,fastdfs基本配置封装,启动类,静态页面,properties配置文件,pom
文件
1、pom依赖

<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.neo</groupId>
    <artifactId>spring-boot-fastDFS</artifactId>
    <packaging>jar</packaging>
    <version>1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        
  <!-- https://mvnrepository.com/artifact/cn.bestwu/fastdfs-client-java -->
<dependency>
    <groupId>cn.bestwu</groupId>
    <artifactId>fastdfs-client-java</artifactId>
    <version>1.27</version>
</dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

配置文件
properties

spring.servlet.http.multipart.max-file-size=10MB
spring.servlet.http.multipart.max-request-size=10MB

resources目录下添加fdfs_client.conf文件

connect_timeout = 60
network_timeout = 60
charset = UTF-8
http.tracker_http_port = 8080
http.anti_steal_token = no
http.secret_key = 123456

tracker_server = 192.168.53.85:22122
tracker_server = 192.168.53.86:22122

fastDFS层
fastDFSClient

package com.neo.fastdfs;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoProperties.Storage;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.*;
/**
 * 在使用fastDFS时,直接调用FastDFSClient对应的方法就可以了
 * @author Administrator
 *
 */
public class FastDFSClient {
	private static org.slf4j.Logger logger = LoggerFactory.getLogger(FastDFSClient.class);
//服务器初始化失败
	static {
		try {
			//构建文件路径
			String filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();;
			ClientGlobal.init(filePath);
		} catch (Exception e) {
			logger.error("FastDFS Client Init Fail!",e);
		}
	}

	/**
	 * 使用FastDFS来实现文件上传
	 * @param file
	 * @return
	 */
	public static String[] upload(FastDFSFile file) {
		//日志打印
		logger.info("File Name: " + file.getName() + "File Length:" + file.getContent().length);

		NameValuePair[] meta_list = new NameValuePair[1];
		meta_list[0] = new NameValuePair("author", file.getAuthor());

		long startTime = System.currentTimeMillis();
		String[] uploadResults = null;
		StorageClient storageClient=null;
		try {
			storageClient = getTrackerClient();
			uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
		} catch (IOException e) {
			logger.error("IO Exception when uploadind the file:" + file.getName(), e);
		} catch (Exception e) {
			logger.error("Non IO Exception when uploadind the file:" + file.getName(), e);
		}
		logger.info("upload_file time used:" + (System.currentTimeMillis() - startTime) + " ms");

		if (uploadResults == null && storageClient!=null) {
			logger.error("upload file fail, error code:" + storageClient.getErrorCode());
		}
		String groupName = uploadResults[0];
		String remoteFileName = uploadResults[1];

		logger.info("upload file successfully!!!" + "group_name:" + groupName + ", remoteFileName:" + " " + remoteFileName);
		return uploadResults;
	}
   /**
    * 使用groupName和文件名获取文件信息
    * @param groupName
    * @param remoteFileName
    * @return
    */
	public static FileInfo getFile(String groupName, String remoteFileName) {
		try {
			StorageClient storageClient = getTrackerClient();
			return storageClient.get_file_info(groupName, remoteFileName);
		} catch (IOException e) {
			logger.error("IO Exception: Get File from Fast DFS failed", e);
		} catch (Exception e) {
			logger.error("Non IO Exception: Get File from Fast DFS failed", e);
		}
		return null;
	}
/**
 * 下载文件
 * @param groupName
 * @param remoteFileName
 * @return
 */
	public static InputStream downFile(String groupName, String remoteFileName) {
		try {
			StorageClient storageClient = getTrackerClient();
			byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
			InputStream ins = new ByteArrayInputStream(fileByte);
			return ins;
		} catch (IOException e) {
			logger.error("IO Exception: Get File from Fast DFS failed", e);
		} catch (Exception e) {
			logger.error("Non IO Exception: Get File from Fast DFS failed", e);
		}
		return null;
	}
/**
 * 删除文件
 * @param groupName
 * @param remoteFileName
 * @throws Exception
 */
	public static void deleteFile(String groupName, String remoteFileName)
			throws Exception {
		StorageClient storageClient = getTrackerClient();
		int i = storageClient.delete_file(groupName, remoteFileName);
		logger.info("delete file successfully!!!" + i);
	}

	public static StorageServer[] getStoreStorages(String groupName)
			throws IOException {
		TrackerClient trackerClient = new TrackerClient();
		TrackerServer trackerServer = trackerClient.getConnection();
		return trackerClient.getStoreStorages(trackerServer, groupName);
	}

	public static ServerInfo[] getFetchStorages(String groupName,
												String remoteFileName) throws IOException {
		TrackerClient trackerClient = new TrackerClient();
		TrackerServer trackerServer = trackerClient.getConnection();
		return trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName);
	}

	public static String getTrackerUrl() throws IOException {
		return "http://"+getTrackerServer().getInetSocketAddress().getHostString()+":"+ClientGlobal.getG_tracker_http_port()+"/";
	}

	private static StorageClient getTrackerClient() throws IOException {
		TrackerServer trackerServer = getTrackerServer();
		StorageClient storageClient = new StorageClient(trackerServer, null);
		return  storageClient;
	}

	private static TrackerServer getTrackerServer() throws IOException {
		TrackerClient trackerClient = new TrackerClient();
		TrackerServer trackerServer = trackerClient.getConnection();
		return  trackerServer;
	}
}

fastDFSFile

package com.neo.fastdfs;
/**
 * 初始化封装信息
 * @author Administrator
 *
 */
public class FastDFSFile {
	private String name;

	private byte[] content;

	private String ext;

	private String md5;

	private String author;

	public FastDFSFile(String name, byte[] content, String ext, String height,
					   String width, String author) {
		super();
		this.name = name;
		this.content = content;
		this.ext = ext;
		this.author = author;
	}

	public FastDFSFile(String name, byte[] content, String ext) {
		super();
		this.name = name;
		this.content = content;
		this.ext = ext;

	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public byte[] getContent() {
		return content;
	}

	public void setContent(byte[] content) {
		this.content = content;
	}

	public String getExt() {
		return ext;
	}

	public void setExt(String ext) {
		this.ext = ext;
	}

	public String getMd5() {
		return md5;
	}

	public void setMd5(String md5) {
		this.md5 = md5;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}
}

controller层
GlobalExceptionHandler

package com.neo.controller;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MultipartException.class)
    public String handleError1(MultipartException e, RedirectAttributes redirectAttributes) {
        redirectAttributes.addFlashAttribute("message", e.getCause().getMessage());
        return "redirect:/uploadStatus";

    }
}

UploadController

package com.neo.controller;

import com.neo.fastdfs.FastDFSClient;
import com.neo.fastdfs.FastDFSFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.io.InputStream;

@Controller
public class UploadController {
    private static Logger logger = LoggerFactory.getLogger(UploadController.class);
    /**
     * 导向上传文件页面
     * @return
     */
    @GetMapping("/")
    public String index() {
        return "upload";
    }
    /**
     * 单个文件的上传,调用了savefile()的方法
     * @param file
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/upload") //new annotation since 4.3
    public String singleFileUpload(@RequestParam("file") MultipartFile file,
                                   RedirectAttributes redirectAttributes) {
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
            return "redirect:uploadStatus";
        }
        try {
            // Get the file and save it somewhere
            String path=saveFile(file);
            redirectAttributes.addFlashAttribute("message",
                    "You successfully uploaded '" + file.getOriginalFilename() + "'");
            redirectAttributes.addFlashAttribute("path",
                    "file path url '" + path + "'");
        } catch (Exception e) {
            logger.error("upload file failed",e);
        }
        return "redirect:/uploadStatus";
    }

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

    /**
     * 从multipartfile中读取信息,然后使用fastdfsClient将文件上传到FastDFS集群中
     * @param multipartFile
     * @return
     * @throws IOException
     */
    public String saveFile(MultipartFile multipartFile) throws IOException {
        String[] fileAbsolutePath={};
        String fileName=multipartFile.getOriginalFilename();
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
        byte[] file_buff = null;
        InputStream inputStream=multipartFile.getInputStream();
        if(inputStream!=null){
            int len1 = inputStream.available();
            file_buff = new byte[len1];
            inputStream.read(file_buff);
        }
        inputStream.close();
        FastDFSFile file = new FastDFSFile(fileName, file_buff, ext);
        try {
            fileAbsolutePath = FastDFSClient.upload(file);  //upload to fastdfs
        } catch (Exception e) {
            logger.error("upload file Exception!",e);
        }
        if (fileAbsolutePath==null) {
            logger.error("upload file failed,please upload again!");
        }
        String path=FastDFSClient.getTrackerUrl()+fileAbsolutePath[0]+ "/"+fileAbsolutePath[1];
        return path;
    }
}

FastDFSApplication

package com.neo;

import org.apache.coyote.http11.AbstractHttp11Protocol;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class FastDFSApplication {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(FastDFSApplication.class, args);
    }
    //Tomcat large file upload connection reset
    @Bean
    public TomcatServletWebServerFactory tomcatEmbedded() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
        tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
            if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
                //-1 means unlimited
                ((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
            }
        });
        return tomcat;
    }

}

静态页面
upload.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>

<h1>Spring Boot file upload example</h1>

<form method="POST" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file" /><br/><br/>
    <input type="submit" value="Submit" />
</form>

</body>
</html>

uploadStatus.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>

<h1>Spring Boot - Upload Status</h1>

<div th:if="${message}">
    <h2 th:text="${message}"/>
</div>

<div th:if="${path}">
    <h2 th:text="${path}"/>
</div>

</body>
</html>

访问地址:http://localhost:8080
原博客

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Boot集成FastDFS可以通过以下步骤实现: 1. 添加FastDFS依赖 在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>com.github.tobato</groupId> <artifactId>fastdfs-client</artifactId> <version>1.27.2</version> </dependency> ``` 2. 配置FastDFS连接信息 在application.properties文件中添加以下配置: ```properties # FastDFS配置 fdfs.tracker-list=192.168.1.100:22122,192.168.1.101:22122 fdfs.connect-timeout=500 fdfs.so-timeout=30000 fdfs.read-timeout=60000 ``` 其中,fdfs.tracker-list为FastDFS Tracker服务器列表,可以配置多个,用逗号分隔;fdfs.connect-timeout、fdfs.so-timeout、fdfs.read-timeout分别为连接、读取、写入超时时间。 3. 编写FastDFS文件上传代码 可以通过以下代码实现文件上传: ```java @Service public class FastDFSFileService { @Autowired private FastFileStorageClient fastFileStorageClient; public String uploadFile(MultipartFile file) throws IOException { StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null); return storePath.getFullPath(); } } ``` 其中,FastFileStorageClient是FastDFS提供的文件存储客户端,可以通过@Autowired注入使用;uploadFile方法用于上传文件,返回文件在FastDFS中的路径。 4. 编写FastDFS文件下载代码 可以通过以下代码实现文件下载: ```java @Service public class FastDFSFileService { @Autowired private DownloadByteArray callback; @Autowired private FastFileStorageClient fastFileStorageClient; public byte[] downloadFile(String filePath) { return fastFileStorageClient.downloadFile(filePath, callback); } } ``` 其中,DownloadByteArray是FastDFS提供的文件下载回调接口,可以通过@Autowired注入使用;downloadFile方法用于下载文件,返回文件的字节数组。 以上就是Spring Boot集成FastDFS的基本步骤,可以根据实际需求进行扩展和优化。 ### 回答2: FastDFS是一个开源的分布式文件系统,采用了多台服务器集群来存储文件,并具有高可靠性、高扩展性和高性能的优点。而SpringBoot是一个快速构建企业级应用的开发框架,可以帮助开发者更加便捷地集成第三方库和框架。 在SpringBoot集成FastDFS,需要按照以下步骤进行操作: 1. 添加FastDFS的依赖 在pom.xml文件中,添加FastDFS的依赖: ```xml <dependency> <groupId>com.github.tobato</groupId> <artifactId>fastdfs-client</artifactId> <version>1.27.1</version> </dependency> ``` 2. 配置FastDFS的连接信息 在application.properties(或application.yml)文件中,配置FastDFS的连接信息,如下: ```properties fdfs.tracker-list=192.168.1.100:22122,192.168.1.101:22122 ``` 3. 创建FastDFS的存储客户端 创建FastDFS的存储客户端,代码如下: ```java @Configuration public class FdfsClientConfig { @Bean public DefaultFastFileStorageClient storageClient() { TrackerClient trackerClient = new TrackerClient(); TrackerServer trackerServer = trackerClient.getTrackerServer(); StorageServer storageServer = new StorageServer(trackerServer,null); return new DefaultFastFileStorageClient(trackerServer, storageServer); } } ``` 4. 使用FastDFS存储文件 在使用过程中,调用FastDFS的存储客户端,使用FastDFS存储文件。例如: ```java @Autowired private DefaultFastFileStorageClient storageClient; public String uploadFile(MultipartFile file) throws IOException { StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null); return storePath.getFullPath(); } ``` 在以上代码中,首先注入FastDFS的存储客户端,然后调用其uploadFile方法,将文件存储到FastDFS中,并返回文件的路径。 通过以上四步,就可以在SpringBoot中成功集成FastDFS,并使用FastDFS来存储文件,以达到分布式存储和高可靠性的目的。 ### 回答3: SpringBoot是一个快速开发框架,能够快速开发各种类型的Java应用程序。FastDFS是一个轻量级的分布式文件系统,用于存储大文件。本文将介绍如何使用SpringBoot集成FastDFS。 一、搭建FastDFS环境 1. 安装libfastcommon $ tar zxvf libfastcommon-1.0.7.tar.gz $ cd libfastcommon-1.0.7 $ ./make.sh $ sudo ./make.sh install 2. 安装FastDFS $ tar zxvf FastDFS_v5.11.tar.gz $ cd FastDFS $ ./make.sh $ sudo ./make.sh install 3. 配置Tracker服务器 在/etc/fdfs目录下创建tracker.conf文件,内容如下: port=22122 base_path=/var/fdfs/tracker log_level=info run_by_group=fastdfs run_by_user=fastdfs 4. 配置Storage服务器 在/etc/fdfs目录下创建storage.conf,内容如下: # mount point /mnt/hdd1 /mnt/hdd2 #Base path for file storage base_path=/var/fdfs/storage #Store path for file storge store_path0=/mnt/hdd1 store_path1=/mnt/hdd2 #Storage tracker server tracker_server=192.168.1.1:22122 5. 启动FastDFS服务 在不同的服务器上分别启动Tracker和Storage服务。 $ sudo /etc/init.d/fdfs_trackerd start $ sudo /etc/init.d/fdfs_storaged start 检查服务是否已启动: $ ps aux | grep fdfs 二、SpringBoot集成FastDFS 1. 添加maven依赖 <dependency> <groupId>com.github.tobato</groupId> <artifactId>fastdfs-client</artifactId> <version>1.25.2</version> </dependency> 2. 配置文件 spring: #fastdfs配置 tracker-list: 192.168.1.1:22122 3. 编写代码 使用FastDFS需要创建TrackerClient和StorageClient两个对象。 通过TrackerClient对象可以得到Storage服务器地址。 通过StorageClient对象上传文件和下载文件。 上传: StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), fileExtName, null); String fullPath = storePath.getFullPath(); 下载: byte[] bytes = storageClient.downloadFile(group, path); return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).contentLength(bytes.length).body(bytes); 通过以上步骤,即可快速集成FastDFSSpringBoot中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值