使用Spring Boot集成FastDFS的示例代碼
這篇文章我們介紹如何使用Spring Boot將文件上傳到分布式文件系統(tǒng)FastDFS中。
這個項目會在上一個項目的基礎(chǔ)上進行構(gòu)建。
1、pom包配置
我們使用Spring Boot最新版本1.5.9、jdk使用1.8、tomcat8.0。
<dependency> <groupId>org.csource</groupId> <artifactId>fastdfs-client-java</artifactId> <version>1.27-SNAPSHOT</version> </dependency>
加入了fastdfs-client-java包,用來調(diào)用FastDFS相關(guān)的API。
2、配置文件
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
配置文件設(shè)置了連接的超時時間,編碼格式以及tracker_server地址等信息
詳細內(nèi)容參考:fastdfs-client-java
3、封裝FastDFS上傳工具類
封裝FastDFSFile,文件基礎(chǔ)信息包括文件名、內(nèi)容、文件類型、作者等。
public class FastDFSFile {
private String name;
private byte[] content;
private String ext;
private String md5;
private String author;
//省略getter、setter
封裝FastDFSClient類,包含常用的上傳、下載、刪除等方法。
首先在類加載的時候讀取相應(yīng)的配置信息,并進行初始化。
static {
try {
String filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();;
ClientGlobal.init(filePath);
trackerClient = new TrackerClient();
trackerServer = trackerClient.getConnection();
storageServer = trackerClient.getStoreStorage(trackerServer);
} catch (Exception e) {
logger.error("FastDFS Client Init Fail!",e);
}
}
文件上傳
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;
try {
storageClient = new StorageClient(trackerServer, storageServer);
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) {
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;
}
使用FastDFS提供的客戶端storageClient來進行文件上傳,最后將上傳結(jié)果返回。
根據(jù)groupName和文件名獲取文件信息。
public static FileInfo getFile(String groupName, String remoteFileName) {
try {
storageClient = new StorageClient(trackerServer, storageServer);
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;
}
下載文件
public static InputStream downFile(String groupName, String remoteFileName) {
try {
storageClient = new StorageClient(trackerServer, storageServer);
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;
}
刪除文件
public static void deleteFile(String groupName, String remoteFileName)
throws Exception {
storageClient = new StorageClient(trackerServer, storageServer);
int i = storageClient.delete_file(groupName, remoteFileName);
logger.info("delete file successfully!!!" + i);
}
使用FastDFS時,直接調(diào)用FastDFSClient對應(yīng)的方法即可。
4、編寫上傳控制類
從MultipartFile中讀取文件信息,然后使用FastDFSClient將文件上傳到FastDFS集群中。
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;
}
請求控制,調(diào)用上面方法saveFile()。
@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";
}
上傳成功之后,將文件的路徑展示到頁面,效果圖如下:

在瀏覽器中訪問此Url,可以看到成功通過FastDFS展示:

這樣使用Spring Boot 集成FastDFS的案例就完成了。
示例代碼-github
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
java關(guān)于并發(fā)模型中的兩種鎖知識點詳解
在本篇文章了小編給大家整理的是一篇關(guān)于java關(guān)于并發(fā)模型中的兩種鎖知識點詳解內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。2021-04-04
官方詳解HDFS?Balancer工具主要調(diào)優(yōu)參數(shù)
這篇文章主要為大家介紹了HDFS?Balancer工具主要調(diào)優(yōu)參數(shù)的?官方詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-03-03
Java 數(shù)據(jù)結(jié)構(gòu)中二叉樹前中后序遍歷非遞歸的具體實現(xiàn)詳解
樹是一種重要的非線性數(shù)據(jù)結(jié)構(gòu),直觀地看,它是數(shù)據(jù)元素(在樹中稱為結(jié)點)按分支關(guān)系組織起來的結(jié)構(gòu),很象自然界中的樹那樣。樹結(jié)構(gòu)在客觀世界中廣泛存在,如人類社會的族譜和各種社會組織機構(gòu)都可用樹形象表示2021-11-11
深入分析JAVA Synchronized關(guān)鍵字
這篇文章主要介紹了析JAVA Synchronized關(guān)鍵字的相關(guān)知識,文中代碼非常詳細,幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-06-06
SpringBoot中的@PostConstruct注解詳細解析
這篇文章主要介紹了SpringBoot中的@PostConstruct注解詳細解析,@PostConstruct注解,主要用于在Spring容器啟動時執(zhí)行某些操作或者任務(wù),@PostConstruct注解一般放在BEAN的方法上,一旦BEAN初始化完成之后,將會調(diào)用這個方法,需要的朋友可以參考下2024-01-01
關(guān)于SpingMVC的<context:component-scan>包掃描踩坑記錄
這篇文章主要介紹了關(guān)于SpingMVC的<context:component-scan>包掃描踩坑記錄,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03
Spring WebFlux實現(xiàn)參數(shù)校驗的示例代碼
請求參數(shù)校驗,在實際的應(yīng)用中很常見,網(wǎng)上的文章大部分提供的使用注解的方式做參數(shù)校驗。本文主要介紹 Spring Webflux Function Endpoint 使用 Spring Validation 來校驗請求的參數(shù)。感興趣的可以了解一下2021-08-08

