1、本例为springboot集成fastdfs服务器案例,需要事先安装好fastdfs服务器
2、添加pom依赖
<!-- https://mvnrepository.com/artifact/org.csource/fastdfs-client-java -->
<dependency>
<groupId>org.csource</groupId>
<artifactId>fastdfs-client-java</artifactId>
<version>1.27-SNAPSHOT</version>
</dependency>
maven官网上给出的是1.27.RELEASE版本,但是通过仓库是下载不下来的,需要本地进行依赖jar包的下载,
详细参考:https://blog.csdn.net/moxiaomo0804/article/details/94479573
3、在src/main/resource下添加fdfs_client.conf文件,如下配置
#默认值为30s
connect_timeout = 10
#默认值为30s
network_timeout = 30
charset = UTF-8
http.tracker_http_port = 80
# token 防盗链功能
http.anti_steal_token = true
http.secret_key = FastDFS1234567890
tracker_server = 172.xx.xx.xx:22122
4、编写dto类FastDFSFile
package com.zw.dto;
public class FastDFSFile {
private String name;//文件名
private byte[] content; //文件的内容,字节数组
private String ext; //文件扩展名,不包含(.)
private String md5; //加密
private String author;
public FastDFSFile() {
}
public FastDFSFile(String name, byte[] content, String ext) {
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;
}
}
5、编写工具类FastDFSClient
package com.zw.util;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import com.zw.dto.FastDFSFile;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
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);
}
}
/**
* 文件上传
* @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();
//upload_file()三个参数:@param fileContent ①:文件的内容,字节数组 ②:文件扩展名 ③文件扩展信息 数组
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;
}
/**
* 查询文件信息
* @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;
}
/**
* 删除文件
* ==0表示成功
* @param groupName 组名 如:group1
* @param remoteFileName 不带组名的路径名称 如:M00/00/00/wKgRsVjtwpSAXGwkAAAweEAzRjw471.jpg
* @throws Exception
*/
public static int deleteFile(String groupName, String remoteFileName)
throws Exception {
StorageClient storageClient = getTrackerClient();
return storageClient.delete_file(groupName, remoteFileName);
}
/**
* 获取storage
* @param groupName 组名
* @return
* @throws IOException
*/
public static StorageServer[] getStoreStorages(String groupName) throws IOException {
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
return trackerClient.getStoreStorages(trackerServer, groupName);
}
/**
*
* @param groupName
* @param remoteFileName
* @return
* @throws IOException
*/
public static ServerInfo[] getFetchStorages(String groupName,String remoteFileName) throws IOException {
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
return trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName);
}
/**
* 获取reacker地址
* @return
* @throws IOException
*/
public static String getTrackerUrl() throws IOException {
return "http://"+getTrackerServer().getInetSocketAddress().getHostString()+":"+ ClientGlobal.getG_tracker_http_port()+"/";
}
/**
* 获取tracker连接
* @return
* @throws IOException
*/
private static StorageClient getTrackerClient() throws IOException {
TrackerServer trackerServer = getTrackerServer();
StorageClient storageClient = new StorageClient(trackerServer, null);
return storageClient;
}
/**
* 获取tracker服务
* @return
* @throws IOException
*/
private static TrackerServer getTrackerServer() throws IOException {
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
return trackerServer;
}
}
6、编写controller进行测试
package com.zw.controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.csource.fastdfs.FileInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.zw.dto.FastDFSFile;
import com.zw.util.FastDFSClient;
import com.zw.util.FastdfsClientUtil;
@Controller
@RequestMapping("/fastdfs2")
public class FastdfsController {
private final Logger logger = LoggerFactory.getLogger(FastdfsController.class);
@Autowired
private FastdfsClientUtil fastdfsClientUtil;
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;
}
@RequestMapping("/upload") //new annotation since 4.3
@ResponseBody
public String singleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:uploadStatus";
}
String path = null;
try {
// Get the file and save it somewhere
path=saveFile(file);
} catch (Exception e) {
logger.error("upload file failed",e);
}
return path;
}
@RequestMapping("/detail") //new annotation since 4.3
@ResponseBody
public FileInfo singleFileUpload(String groupName, String remoteFileName) {
FileInfo file = null;
try {
// Get the file and save it somewhere
file = FastDFSClient.getFile(groupName, remoteFileName);
} catch (Exception e) {
logger.error("upload file failed",e);
}
return file;
}
@RequestMapping("/download")
@ResponseBody
public void download(String groupName, String remoteFileName,HttpServletResponse response) {
InputStream in = null;
try {
// Get the file and save it somewhere
in = FastDFSClient.downFile(groupName, remoteFileName);
byte[] buffer = new byte[in.available()];
in.read(buffer);
// File targetFile = new File("src/main/resources/targetFile.tmp");
// OutputStream outStream = new FileOutputStream(targetFile);
// outStream.write(buffer);
// outStream.flush();
response.setContentLength(buffer.length);
response.setHeader("Content-Disposition", "attachment;filename=" + remoteFileName);
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(buffer);
outputStream.flush();
} catch (Exception e) {
logger.error("upload file failed",e);
}
}
@RequestMapping("/delete")
@ResponseBody
public int delete(String groupName, String remoteFileName) {
int deleteFile = 0;
try {
// Get the file and save it somewhere
deleteFile = FastDFSClient.deleteFile(groupName, remoteFileName);
} catch (Exception e) {
logger.error("upload file failed",e);
}
return deleteFile;
}
}
7、启动服务,测试