不积跬步,无以至千里;不积小流,无以成江海。

FastDFS JAVA客户端的使用

JAVA 康康 1828℃ 0评论

1.引用fastdfs-client.jar 包 可使用maven:

com.github.tobato
fastdfs-client1.25.2-RELEASE

2.客户端配置文件client.conf:

connect_timeout = 2
network_timeout = 30
charset = UTF-8
http.tracker_http_port = 9090
http.anti_steal_token = no
http.secret_key = FastDFS1234567890
#跟踪器服务地址-跟踪器主要做调度工作,在访问上起负载均衡的作用。
tracker_server = ip:22122 #取决于文件服务器服务端地址

3.工具类如下:

 

public class FastDFSUtil {

private static Map<String,Object> retMap = null;

/**
*
* Description:上传服务器本地文件-通过Linux客户端
* @author: 陈维康
* @date: 2016年11月18日
* @param filePath 文件绝对路径
* @return
*/
public static Map<String,Object> uploadLocalFile(String filePath){

retMap = new HashMap<String, Object>();

//String command = "fdfs_upload_file /etc/fdfs/client.conf /chni/data/resource/tcm/file/001000000000100002TCM.pdf";

String command = "fdfs_upload_file /etc/fdfs/client.conf "+filePath;

String fileId="";

try {

//调用javaAPI 执行linux命令上传文件

Process process = Runtime.getRuntime().exec(command);

InputStreamReader ir=new InputStreamReader(process.getInputStream());

BufferedReader input = new BufferedReader (ir);

String line;

if ((line = input.readLine ()) != null){

fileId = line;
}

if(fileId.contains("M00")){

retMap.put("code", "0000");

retMap.put("group", fileId.substring(0,6));

retMap.put("msg",fileId.substring(7,fileId.length()));
}else{

retMap.put("code", "0001"); //上传错误

retMap.put("msg", fileId); //返回信息
}

} catch (Exception e {

retMap.put("code", "0002");

retMap.put("msg", e.getMessage());
}

return retMap;

}

/**
*
* Description: 直接通过fdfs java客户端上传到服务器-读取本地文件上传
* @author: 陈维康
* @date: 2016年11月18日
* @param filePath 本地文件绝对路径
* @return
*/
public static Map<String,Object> upload(String filePath){
retMap = new HashMap<String, Object>();
File file = new File(filePath);
if(file.isFile()){
try {

String tempFileName = file.getName();

//读取fastDFS客户端配置文件

ClassPathResource cpr = new ClassPathResource("fdfs_client.conf");

ClientGlobal.init(cpr.getClassLoader().getResource("fdfs_client.conf").getPath());

byte[] fileBuff = FastDFSUtil.getBytesFromFile(file);

String fileId = "";

//截取后缀

String fileExtName = tempFileName.substring(tempFileName.lastIndexOf(".")+1);

//建立连接

TrackerClient tracker = new TrackerClient();

TrackerServer trackerServer = tracker.getConnection();

StorageServer storageServer = null;

StorageClient1 client = new StorageClient1(trackerServer, storageServer);
//设置元信息
NameValuePair[] metaList = new NameValuePair[3];
//原始文件名称
metaList[0] = new NameValuePair("fileName", tempFileName);
//文件后缀
metaList[1] = new NameValuePair("fileExtName", fileExtName);
//文件大小
metaList[2] = new NameValuePair("fileLength", String.valueOf(file.length()));
//开始上传文件
fileId = client.upload_file1(fileBuff, fileExtName, metaList);
if(!fileId.equals("")&&fileId!=null){
retMap.put("code", "0000");
retMap.put("group", fileId.substring(0,6));
retMap.put("msg",fileId.substring(7,fileId.length()));
}else{
retMap.put("code", "0003");
retMap.put("msg","error:上传失败!");
}

} catch (Exception e) {
e.printStackTrace();
retMap.put("code", "0002");
retMap.put("msg",e.getMessage());
}
}else{
retMap.put("code", "0001");
retMap.put("msg","error:本地文件不存在!");
}
return retMap;
}

/**
*
* Description:远程选择上传文件-通过MultipartFile
* @author: Chen
* @date: 2016年11月1日
* @param file 文件流
* @return
*/
public static Map<String,Object> upload(MultipartFile file){
retMap = new HashMap<String, Object>();
try {
if(file.isEmpty()){
retMap.put("code", "0001");
retMap.put("msg","error:文件为空!");
}else{
String tempFileName = file.getOriginalFilename();
//读取fastDFS客户端配置文件
ClassPathResource cpr = new ClassPathResource("fdfs_client.conf");
ClientGlobal.init(cpr.getClassLoader().getResource("fdfs_client.conf").getPath());
byte[] fileBuff = file.getBytes();
String fileId = "";
//截取后缀
String fileExtName = tempFileName.substring(tempFileName.lastIndexOf(".")+1);
//建立连接
TrackerClient tracker = new TrackerClient();
TrackerServer trackerServer = tracker.getConnection();
StorageServer storageServer = null;
StorageClient1 client = new StorageClient1(trackerServer, storageServer);
//设置元信息
NameValuePair[] metaList = new NameValuePair[3];
//原始文件名称
metaList[0] = new NameValuePair("fileName", tempFileName);
//文件后缀
metaList[1] = new NameValuePair("fileExtName", fileExtName);
//文件大小
metaList[2] = new NameValuePair("fileLength", String.valueOf(file.getSize()));
//开始上传文件
fileId = client.upload_file1(fileBuff, fileExtName, metaList);
if(!fileId.equals("")&&fileId!=null){
retMap.put("code", "0000");
retMap.put("group", fileId.substring(0,6));
retMap.put("msg",fileId.substring(7,fileId.length()));
}else{
retMap.put("code", "0003");
retMap.put("msg","error:上传失败!");
}
}
} catch (Exception e) {
retMap.put("code", "0002");
retMap.put("msg","error:文件上传失败!");
}
return retMap;
}

/**
*
* Description:
* @author: Chen
* @date: 2016年11月1日
* @param response
* @param filepath 数据库存的文件路径
* @param downname 下载后的名称
* filepath M00/开头的文件路径
* group 文件所在的组 如:group0
* @throws IOException
*/
public static void download(HttpServletResponse response ,String group ,String filepath , String downname) throws IOException{
//retMap = new HashMap<String, Object>();
PrintWriter print = response.getWriter();
try {
//读取fastDFS客户端配置文件
ClassPathResource cpr = new ClassPathResource("fdfs_client.conf");
ClientGlobal.init(cpr.getClassLoader().getResource("fdfs_client.conf").getPath());
TrackerClient tracker = new TrackerClient();
TrackerServer trackerServer = tracker.getConnection();
StorageServer storageServer = null;
StorageClient storageClient = new StorageClient(trackerServer, storageServer);
byte[] b = storageClient.download_file(group , filepath);
if(b==null){
System.out.println("Error1 : file not Found!");
print.write("Error1 : file not Found!");
}else{
System.out.println("下载文件..");
downname = new String(downname.getBytes("utf-8"), "ISO8859-1" );
response.setHeader("Content-Disposition", "attachment;fileName="+downname);
OutputStream out = response.getOutputStream();
out.write(b);
out.close();
}
} catch (Exception e) {
e.printStackTrace();
print.write("Error2 : "+e.getMessage());
}
}

/**
*
* Description:删除文件
* @author: Chen
* @date: 2016年11月18日
* @param group 文件分组, filepath 已M00/ 开头的文件路径
* @return
*/
public static Map<String,Object> delete(String group , String filepath){
retMap = new HashMap<String, Object>();
try {
//读取fastDFS客户端配置文件
ClassPathResource cpr = new ClassPathResource("fdfs_client.conf");
ClientGlobal.init(cpr.getClassLoader().getResource("fdfs_client.conf").getPath());
TrackerClient tracker = new TrackerClient();
TrackerServer trackerServer = tracker.getConnection();
StorageServer storageServer = null;
StorageClient storageClient = new StorageClient(trackerServer, storageServer);
int i = storageClient.delete_file(group, filepath);
System.out.println( i==0 ? "删除成功" : "删除失败:"+i);
if(i==0){
retMap.put("code","0000");
retMap.put("msg","删除成功!");
}else{
retMap.put("code","0001");
retMap.put("msg","文件不存在!");
}
} catch (Exception e) {
e.printStackTrace();
retMap.put("code","0002");
retMap.put("msg","删除失败!");
}
return retMap;

}

public static byte[] getBytesFromFile(File f){
if (f == null) {
return null;
}
try {
FileInputStream stream = new FileInputStream(f);
ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
for (int n;(n = stream.read(b)) != -1;) {
out.write(b, 0, n);
}
stream.close();
out.close();
return out.toByteArray();
} catch (IOException e) {

}
return null;
}
}

 

转载请注明:左手代码右手诗 » FastDFS JAVA客户端的使用

喜欢 (0)or分享 (0)
发表我的评论
取消评论

 

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址