Java 整合 FastDFS
整体逻辑
在页面上传文件后台由 MultipartFile 接收,接着将 MultipartFile 文件转发为 FastDFS 文件封装类 FastDFSFile,调用 FastDFSClient 类的封装方法,将文件(FastDFSFile)上传到 FastDFS 集群中,成功后集群中文件存储位置返回到页面。
依赖
<dependency>
<groupId>org.csource</groupId>
<artifactId>fastdfs-client-java</artifactId>
<version>1.27-SNAPSHOT</version>
</dependency>
FastDFS 配置
- 项目 resources 目录下添加
fdfs_client.conf
文件:
connect_timeout = 60 # 连接超时时间
network_timeout = 60 # 网络超时时间
charset = UTF-8 # 编码格式
http.tracker_http_port = 8080 #tracker 端口
http.anti_steal_token = no #token 防盗链功能
http.secret_key = 123456 #密钥
# tracer server 列表,多个 tracer server 的话,分行列出
tracker_server = 192.168.53.85:22122
tracker_server = 192.168.53.86:22122
实际使用时删除注释信息,否则会报错
封装 FastDFS 上传工具类
public class FastDFSFile {
private String name;
private byte[] content;
private String ext;
private String md5;
private String author;
//省略getter、setter
}
封装 FastDFSClient 工具类
public class FastDFSClient {
private static 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 = getStorageClient();
uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
} 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.info("upload file fail, error code:" + storageClient.getErrorCode());
}
logger.info("upload file successfully!!!" + "group_name:" + uploadResults[0] + ", remoteFileName:" + " " + uploadResults[1]);
return uploadResults;
}
/**
* 获取 StorageClient
*
* @return
* @throws IOException
*/
public static StorageClient getStorageClient() throws IOException {
TrackerServer trackerServer = getTrackerServer();
StorageClient storageClient = new StorageClient(trackerServer, null);
return storageClient;
}
/**
* 获取 TrackerServer
*
* @return
* @throws IOException
*/
private static TrackerServer getTrackerServer() throws IOException {
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
return trackerServer;
}
/**
* 根据 groupName 和文件名获取文件信息
*
* @param groupName
* @param remoteFileName
* @return
*/
public static FileInfo getFile(String groupName, String remoteFileName) {
try {
StorageClient storageClient = getStorageClient();
return storageClient.get_file_info(groupName, remoteFileName);
} catch (Exception e) {
logger.error("Non IO Exception: Get File from Fast DFS failed", e);
}
return null;
}
/**
* 根据 storageClient 的 API 获取文件的字节流并返回
*
* @param groupName
* @param remoteFileName
* @return
*/
public static InputStream downFile(String groupName, String remoteFileName) {
try {
StorageClient storageClient = getStorageClient();
byte[] bytes = storageClient.download_file(groupName, remoteFileName);
InputStream ins = new ByteArrayInputStream(bytes);
return ins;
} 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 = getStorageClient();
int i = storageClient.delete_file(groupName, remoteFileName);
logger.info("delete file successfully!!!" + i);
}
/**
* 生成文件地址
*
* @return
* @throws IOException
*/
public static String getTrackerUrl() throws IOException {
return "http://" + getTrackerServer().getInetSocketAddress().getHostString() + ":" + ClientGlobal.getG_tracker_http_port() + "/";
}
}
FastDFS 工具调用
@Controller
@RequestMapping("/fastdfs")
public class FastDFSController {
private static Logger logger = LoggerFactory.getLogger(FastDFSController.class);
/**
* 访问上传页面
*
* @return
*/
@GetMapping("/toUp")
public String toUp() {
return "fastdfs/toUp";
}
/**
* 上传文件
* @param file
* @param map
* @return
*/
@PostMapping("/singleFileUpload")
public String singleFileUpload(@RequestParam("file") MultipartFile file,
ModelMap map) {
if (file.isEmpty()) {
map.addAttribute("message", "Please select a file to upload");
return "/fastdfs/uploadStatus";
}
try {
String path=saveFile(file);
map.addAttribute("message",
"You successfully uploaded '" + file.getOriginalFilename() + "'");
map.addAttribute("path","file path url '" + path + "'");
} catch (Exception e) {
logger.error("upload file failed",e);
}
return "/fastdfs/uploadStatus";
}
/**
* 获取文件信息
* @param groupName: group1
* @param remoteFileName: M00/00/00/wKgBoF2kDXWAHdAKAAJsTdA9W_o579.png
* @return
*/
@PostMapping("/getFileInfo")
public String getFileInfo(String groupName, String remoteFileName){
FileInfo fileInfo = FastDFSClient.getFile(groupName, remoteFileName);
System.out.println("CRC32签名:" + fileInfo.getCrc32());
System.out.println("文件大小:" + fileInfo.getFileSize());
System.out.println("服务器地址:" + fileInfo.getSourceIpAddr());
System.out.println("创建时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(fileInfo.getCreateTimestamp()));
return "/fastdfs/uploadStatus";
}
/**
* 获取元数据信息
* @param groupName
* @param remoteFileName
* @return
* @throws Exception
*/
@PostMapping("/getMetaData")
public String getMetaData(String groupName, String remoteFileName)throws Exception{
NameValuePair[] get_metadata = FastDFSClient.getStorageClient().get_metadata(groupName,
remoteFileName);
for (NameValuePair nameValuePair: get_metadata) {
System.out.println("name: " + nameValuePair.getName() + " value: " + nameValuePair.getValue());
}
return "/fastdfs/uploadStatus";
}
/**
* 上传文件
*
* @param multipartFile
* @return
*/
private String saveFile(MultipartFile multipartFile) throws Exception {
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 lenl = inputStream.available();
file_buff = new byte[lenl];
inputStream.read(file_buff);
}
inputStream.close();
FastDFSFile file = new FastDFSFile(filename, file_buff, ext);
try {
fileAbsolutePath = FastDFSClient.upload(file);
} catch (Exception e) {
logger.error("upload file failed,please upload again!");
}
String path = FastDFSClient.getTrackerUrl() + fileAbsolutePath[0] + "/" + fileAbsolutePath[1];
return path;
}
}
解决Maven无法下载fastdfs-client-java依赖
# 下载 fastdfs-client-java 包
git clone https://github.com/happyfish100/fastdfs-client-java.git
# 进入下载好的fastdfs-client-java 解压
$ cd /fastdfs-client-java
# 使用maven打包jar
$ mvn clean install