FasfDFS整合Java实现文件上传下载功能实例详解
https://www.jb51.net/article/120675.htm
在上篇文章给大家介绍了FastDFS安装和配置整合Nginx-1.13.3的方法,大家可以点击查看下。
今天使用Java代码实现文件的上传和下载。对此作者提供了Java API支持,下载fastdfs-client-java将源码添加到项目中。或者在Maven项目pom.xml文件中添加依赖
<dependency>
<groupId>org.csource</groupId>
<artifactId>fastdfs-client-java</artifactId>
<version>1.27-SNAPSHOT</version>
</dependency>
一 : 添加配置文件
当完成以上操作之后可以添加链接FastDFS服务器的配置文件 fastdfs-client.properties
fastdfs.connect_timeout_in_seconds = 5
fastdfs.network_timeout_in_seconds = 30
fastdfs.charset = UTF-8
fastdfs.http_anti_steal_token = false
fastdfs.http_secret_key = FastDFS1234567890
fastdfs.http_tracker_http_port = 80
fastdfs.tracker_servers = 192.168.1.7:22122
因为项目中只使用properties 格式文件,如果需要更多的配置信息,可以查看官方的配置信息
注: 1. 其他的配置项为可选,fastdfs.tracker_servers 为必须选项
2. 多个tracker_servers可以使用逗号“ , ”分隔
二 : 加载配置文件
1. 测试加载配置文件
@Test
public void initConifg() throws Exception {
// 加载配置文件
ClientGlobal.initByProperties("config/fastdfs-client.properties");
System.out.println("ClientGlobal.configInfo():" + ClientGlobal.configInfo());
}
2. 输出结果
ClientGlobal.configInfo():{
g_connect_timeout(ms) = 5000
g_network_timeout(ms) = 30000
g_charset = UTF-8
g_anti_steal_token = false
g_secret_key = FastDFS1234567890
g_tracker_http_port = 80
trackerServers = 192.168.1.7:22122
}
当出现上面和配置文件一致的输出结果时候,说明加载配置文件已经成功。
三:功能实现
由于是使用Junit做测试,为了方便在开始执行之前,初始化配置文件和获取连接,同时没有捕获异常全部抛出
1.初始化连接信息
//成员变量
TrackerServer trackerServer = null;
StorageServer storageServer = null;
StorageClient storageClient = null;
/**
* 初始化连接信息
* @author: wrh45
* @date: 2017年8月5日下午8:08:57
*/
@Before
public void init() throws Exception {
// 加载配置文件
ClientGlobal.initByProperties("config/fastdfs-client.properties");
// 获取连接
TrackerClient trackerClient = new TrackerClient();
trackerServer = trackerClient.getConnection();
storageClient = new StorageClient(trackerServer, storageServer);
}
注: 如果出现连接超时异常:java.net.SocketTimeoutException: connect timed out
1 .查看服务器地址和端口是否正确
2 .请查看服务器TrackerServer和StorageServer服务端口是否开启。默认为22122和23000
2.上传文件
/**
* 上传图片
* @throws Exception
* @author: wrh45
* @date: 2017年8月5日下午7:09:23
*/
@Test
public void uploadFileOfByte() throws Exception {
// 获取文件字节信息
file = new File("src/test/resources/pic/Ace.jpg");
FileInputStream inputStream = new FileInputStream(file);
byte[] file_buff = new byte[(int) file.length()];
inputStream.read(file_buff);
// 获取文件扩展名
String fileName = file.getName();
String extName = null;
if (fileName.contains(".")) {
extName = fileName.substring(fileName.lastIndexOf(".") + 1);
} else {
return;
}
// 图片元数据,如果设置为空,那么服务器上不会生成-m的原数据文件
NameValuePair[] meta_list = new NameValuePair[2];
meta_list[0] = new NameValuePair("fileName", "测试专用");
meta_list[1] = new NameValuePair("length", "测试专用");
// 文件上传,返回组名和访问地址
String[] upload_file = storageClient.upload_file(file_buff, extName, meta_list);
System.out.println(Arrays.asList(upload_file));
}
下面是执行结果

已经将图片上传到服务器,同时返回了图片地址。那么通过这个地址试试能否访问
OK,在浏览器输入地址后,成功返回了图片信息

3.下载文件
这里通过storageClient下载文件,然后将数据存储到本地。如果通过浏览器下载,同理将数据写入文件即可
/**
* 下载图片
* @throws Exception
* @author: wrh45
* @date: 2017年8月5日下午8:09:10
*/
@Test
public void downLoadFile() throws Exception {
// 下载文件,返回字节数组
byte[] file_buff = storageClient.download_file("group1", "M00/00/00/wKgBB1l-EwyAGvxuAAWkdYkPHEE854.jpg");
// 将数据写文件中
File file = new File("src/test/resources/pic/Ace2.jpg");
FileOutputStream outStream = new FileOutputStream(file);
outStream.write(file_buff);
outStream.flush();
outStream.close();
}
下面是执行结果,不出意外是可以成功执行的

4.获取元数据信息
/**
* 元数据信息
* @throws Exception
* @author: wrh45
* @date: 2017年8月5日下午8:09:38
*/
@Test
public void metaData() throws Exception {
// 上传图片的时候,元数据若为空将无法生存-m的原数据文件。获取时候此处将抛出NullPointerException
NameValuePair[] get_metadata = storageClient.get_metadata("group1",
"M00/00/00/wKgBB1l-EwyAGvxuAAWkdYkPHEE854.jpg");
for (NameValuePair nameValuePair: get_metadata) {
System.out.println("name: " + nameValuePair.getName() + " value: " + nameValuePair.getValue());
}
}
以下是执行结果,获取到的数据和上传的数据一样
name: fileName value: 测试专用
name: length value: 测试专用
5.获取文件信息
/**
* 获取文件信息
* @author: wrh45
* @date: 2017年8月7日下午9:02:47
*/
@Test
public void getFileInfo() throws Exception {
FileInfo fileInfo = storageClient.get_file_info("group1", "M00/00/00/wKgBB1l-EwyAGvxuAAWkdYkPHEE854.jpg");
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()));
}
输出结果
CRC32签名:-1995498431
文件大小:369781
服务器地址:192.168.1.7
创建时间:2017-08-07 20-24-56
6.删除文件
当数据测试完整之后,试试能否删除吧
/**
* 删除文件
* @throws Exception
* @author: wrh45
* @date: 2017年8月7日下午9:10:04
*/
@Test
public void deleteFile() throws Exception {
// 返回0成功,否则返回错误吗
int code = storageClient.delete_file("group1", "M00/00/00/wKgBB1l-EwyAGvxuAAWkdYkPHEE854.jpg");
System.out.println(code);
}
删除之后输出结果为0,如果出现非0结果,那么返回的是错误代码
以上是Java实现上传下载等功能的代码,如果需要可以封装成工具类使用。
以下是个人封装好的工具类
/**
* 上传文件工具类
* @ClassName: FileUploadUtils
* @author wrh45
* @date 2017年8月8日下午4:14:31
*/
public class FileUploadUtils {
private static TrackerClient trackerClient = null;
private static TrackerServer trackerServer = null;
private static StorageServer storageServer = null;
private static StorageClient storageClient = null;
private static final String groupName = "group1";
static {
// 加载配置文件
try {
ClientGlobal.initByProperties("config/fastdfs-client.properties");
// System.out.println("ClientGlobal.configInfo():" +
// ClientGlobal.configInfo());
} catch (IOException | MyException e) {
e.printStackTrace();
System.out.println("load config file fail");
}
}
/*
* 初始化连接数据
*/
private static void init() {
try {
trackerClient = new TrackerClient();
trackerServer = trackerClient.getConnection();
storageClient = new StorageClient(trackerServer, storageServer);
} catch (IOException e) {
e.printStackTrace();
System.out.println("init fail");
}
}
/**
* 上传文件
* @param filePath 文件路径
* @param fileName 文件名称
* @return 文件存储信息
* @author: wrh45
* @date: 2017年8月5日下午11:10:38
*/
public static String[] uploadFile(String filePath, String fileName) {
return uploadFile(null, filePath, fileName);
}
/**
* 上传文件
* @param fileBuff 文件字节数组
* @param fileName 文件名称
* @return 文件存储信息
* @author: wrh45
* @date: 2017年8月5日下午11:10:38
*/
public static String[] uploadFile(byte[] fileBuff, String fileName) {
return uploadFile(fileBuff, null, fileName);
}
/**
* 上传文件
* @param file_buff 文件字节数组
* @param filePath 文件路径
* @param fileName 文件名称
* @return 文件存储信息
* @author: wrh45
* @date: 2017年8月5日下午10:58:19
*/
private static String[] uploadFile(byte[] fileBuff, String filePath, String fileName) {
try {
if (fileBuff == null && filePath == null) {
return new String[0];
}
// 初始化数据
if (storageClient == null) {
init();
}
// 获取文件扩展名称
String fileExtName = "";
if (fileName != null && !"".equals(fileName) && fileName.contains(".")) {
fileExtName = fileName.substring(fileName.lastIndexOf(".") + 1);
} else {
return new String[0];
}
// 设置图片元数据
NameValuePair[] metaList = new NameValuePair[3];
metaList[0] = new NameValuePair("fileName", fileName);
metaList[1] = new NameValuePair("fileExtName", fileExtName);
metaList[2] = new NameValuePair("fileSize", String.valueOf(fileBuff.length));
// 上传文件
String[] uploadFile = null;
if (fileBuff != null && filePath == null) {
if (fileBuff.length == 0) {
return new String[0];
}
uploadFile = storageClient.upload_file(fileBuff, fileExtName, metaList);
} else {
//路径匹配Windown和Linux
if ("".equals(filePath) || !(filePath.matches("^[a-zA-Z]:{1}([\u4e00-\u9fa5\\w/_\\\\-]+)$") || filePath.matches("^(/[\u4e00-\u9fa5\\w_-]+)+$"))) {
return new String[0];
}
uploadFile = storageClient.upload_file(filePath, fileExtName, metaList);
}
return uploadFile == null ? new String[0] : uploadFile;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (trackerServer != null) {
trackerServer.close();
trackerServer = null;
}
if (storageServer != null) {
storageServer.close();
storageServer = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return new String[0];
}
/**
* 删除服务器文件
* @param remoteFileName 文件在服务器中名称
* @author: wrh45
* @date: 2017年8月6日上午12:15:22
*/
public static int deleteFile(String remoteFileName) {
try {
if (remoteFileName == null || "".equals(remoteFileName) || !remoteFileName.contains(groupName)) {
return -1;
}
if (storageClient == null) {
init();
}
String fileURL = remoteFileName.substring(remoteFileName.indexOf(groupName));
String group = fileURL.substring(0, remoteFileName.indexOf("/") + 1);
String fileName = fileURL.substring(remoteFileName.indexOf("/") + 2);
int code = storageClient.delete_file(group, fileName);
return code;
} catch (Exception e) {
e.printStackTrace();
System.out.println("The File Delete Fail");
}
return -1;
}
/**
* 获取文件信息
* @param groupName 组名
* @param remoteFilename 远程文件名
* @return
* @author: wrh45
* @date: 2017年8月8日上午12:25:26
*/
public static FileInfo getFileInfo(String groupName, String remoteFilename) {
try {
if (storageClient == null) {
init();
}
FileInfo fileInfo = storageClient.get_file_info(groupName, remoteFilename);
return fileInfo;
} catch (Exception e) {
e.printStackTrace();
System.out.println("Get File Info Fail");
}
return null;
}
}
FasfDFS整合Java实现文件上传下载功能实例详解的更多相关文章
- FasfDFS整合Java实现文件上传下载
文章目录 一 : 添加配置文件 二 : 加载配置文件 1. 测试加载配置文件 2. 输出配置文件 三:功能实现 1.初始化连接信 ...
- JavaWeb实现文件上传下载功能实例解析
转:http://www.cnblogs.com/xdp-gacl/p/4200090.html JavaWeb实现文件上传下载功能实例解析 在Web应用系统开发中,文件上传和下载功能是非常常用的功能 ...
- JavaWeb实现文件上传下载功能实例解析 (好用)
转: JavaWeb实现文件上传下载功能实例解析 转:http://www.cnblogs.com/xdp-gacl/p/4200090.html JavaWeb实现文件上传下载功能实例解析 在Web ...
- java实现文件上传下载
喜欢的朋友可以关注下,粉丝也缺. 今天发现已经有很久没有给大家分享一篇技术文章了,于是想了一下给大家分享一篇java实现文件上传下载功能的文章,不喜欢的希望大家勿喷. 想必大家都知道文件的上传前端页面 ...
- CentOS下安装配置NFS并通过Java进行文件上传下载
1:安装NFS (1)安装 yum install nfs-utils rpcbind (2)启动rpcbind服务 systemctl restart rpcbind.service 查看服务状态 ...
- java web 文件上传下载
文件上传下载案例: 首先是此案例工程的目录结构:
- java+大文件上传下载
文件上传下载,与传统的方式不同,这里能够上传和下载10G以上的文件.而且支持断点续传. 通常情况下,我们在网站上面下载的时候都是单个文件下载,但是在实际的业务场景中,我们经常会遇到客户需要批量下载的场 ...
- Struts2实现文件上传下载功能(批量上传)
今天来发布一个使用Struts2上传下载的项目, struts2为文件上传下载提供了好的实现机制, 首先,可以先看一下我的项目截图 关于需要使用的jar包,需要用到commons-fileupload ...
- WEB文件上传下载功能
WEB文件上传下载在日常工作中经常用到的功能 这里用到JS库 http://files.cnblogs.com/meilibao/ajaxupload.3.5.js 上传代码段(HTML) <% ...
随机推荐
- [转帖]Linux中的find(-atime、-ctime、-mtime)指令分析
Linux中的find(-atime.-ctime.-mtime)指令分析 https://www.cnblogs.com/zhangjinjin01/p/5505970.html https://w ...
- Prometheus入门到放弃(7)之redis_exporter部署
redis监控,prometheus需要使用redis_exporter客户端. 这里我们采用docker方式部署,既可以部署在redis所在服务器,也可以部署在其他机器: docker镜像地址:ht ...
- Linux+QT界面开发(含数据库)小结
今天十一国庆节,过了一个很有意义的国庆节,去了龙岗区图书馆,第一次知道了借的书可以在任意分馆归还!这个切实方便了广大读者.针对Linux应用,特意借阅一本:<linux环境下Qt4图形界面与My ...
- gdb调试常用功能
一.gdb中宏定义 macro define list_entry(ptr, type, member) ((type)( (char)ptr - (unsigned long)(&((typ ...
- Scala 函数入门之过程、lazy值和异常
Scala 过程 在Scala中,定义函数时,如果函数体直接包裹在了花括号里面,而没有使用=连接,则函数的返回值类型就是Unit.这样的函数就被称之为过程.过程通常用于不需要返回值的函数. 过程还有 ...
- Linux -- file 命令
1.file命令含义 file命令用于接受一个文件作为参数并执行某些测试,以确定正确的文件类型 2.file命令参数以及实例 (1)file命令查看文件类型 $ file /etc/irbrc /et ...
- Springboot 整合ApachShiro完成登录验证和权限管理
1.前言 做一个系统最大的问题就是安全问题以及权限的问题,如何正确的选择一个安全框架对自己的系统进行保护,这方面常用的框架有SpringSecurity,但考虑到它的庞大和复杂,大多数公司还是会选择 ...
- backpropagation algorithm
搞卷积神经网络的时候突然发现自己不清楚神经网络怎么训练了,满脸黑线,借此机会复习一下把. 首先放一位知乎大佬的解释.https://www.zhihu.com/question/27239198?rf ...
- Asp.netMVC中Ajax.BeginForm上传文件
做一个上传并解压的功能,解压完了回调,解压多少文件.搞了半天用Ajax.BeginForm.各种坑,后来直接放弃 @using (Ajax.BeginForm("UploadFile&quo ...
- CCF 2016-12-1 工资计算
CCF 2016-12-1 工资计算 题目 问题描述 小明的公司每个月给小明发工资,而小明拿到的工资为交完个人所得税之后的工资.假设他一个月的税前工资(扣除五险一金后.未扣税前的工资)为S元,则他应交 ...