用于上传
/***
*
* @Author:xiong
* FastDfs文件上传
****/
public class UploadUtil {
/***
* 文件类路径替换
* @param path
* @return
*/
public static String getConfig(String path){
if(path.startsWith("classpath:")){
path=path.replace("classpath:",UploadUtil.class.getResource("/").getPath());
}
return path;
}
/****
* 文件上传
* trackerconfig:访问tracker的服务配置(tracker的IP和端口)
* filepath:要上传的文件的路径
*/
public static void upload(String trackerconfig,String filepath) throws Exception{
//替换类路径
trackerconfig=getConfig(trackerconfig);
filepath=getConfig(filepath);
//初始化全局参数
ClientGlobal.init(trackerconfig);
//创建一个Tracker客户端
TrackerClient trackerClient = new TrackerClient();
//通过Tracker客户端连接Tracker得到一个服务端对象(连接对象)
TrackerServer trackerServer = trackerClient.getConnection();
//创建一个Storage客户端
StorageClient storageClient = new StorageClient(trackerServer,null);
//远程向Storage上传文件
//storageClient.upload_file("本地需要上传的文件路径","文件的扩展名","其他参数");
String[] uploads = storageClient.upload_file(filepath, null, null);
for (String upload : uploads) {
System.out.println(upload);
}
}
/****
* 文件上传
* trackerconfig:访问tracker的服务配置(tracker的IP和端口)
* buffer:要上传的文件字节数组
* suffix:文件的扩展名,后缀
*/
public static String[] upload(String trackerconfig, byte[] buffer, String suffix) throws Exception{
//替换类路径
trackerconfig=getConfig(trackerconfig);
//初始化全局参数
ClientGlobal.init(trackerconfig);
//创建一个Tracker客户端
TrackerClient trackerClient = new TrackerClient();
//通过Tracker客户端连接Tracker得到一个服务端对象(连接对象)
TrackerServer trackerServer = trackerClient.getConnection();
//创建一个Storage客户端
StorageClient storageClient = new StorageClient(trackerServer,null);
//远程向Storage上传文件
//storageClient.upload_file("文件的字节数组","文件的扩展名","其他参数");
String[] uploads = storageClient.upload_file(buffer,suffix,null);
for (String upload : uploads) {
System.out.println(upload);
}
return uploads;
}
public static void main(String[] args) throws Exception {
String filepath="classpath:1.jpg";
String tracker="classpath:tracker.conf";
upload(tracker,filepath);
}
}