public class FastDFSUtils {
private static Logger logger = Logger.getLogger(FastDFSUtils.class);
static{
try {
ClientGlobal.init("D:/WorkSpace/app-filesystem/conf/fdfs_client.conf");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String uploadFile(String filePath) throws Exception{
String fileId = "";
String fileExtName = "";
if (filePath.contains(".")) {
fileExtName = filePath.substring(filePath.lastIndexOf(".") + 1);
} else {
logger.warn("Fail to upload file, because the format of filename is illegal.");
return fileId;
}
//建立连接
/*.......*/
//上传文件
try {
fileId = client.upload_file1(filePath, fileExtName, null);
} catch (Exception e) {
logger.warn("Upload file \"" + filePath + "\"fails");
}finally{
trackerServer.close();
}
return fileId;
}
public static String uploadSlaveFile(String masterFileId, String prefixName, String slaveFilePath) throws Exception{
String slaveFileId = "";
String slaveFileExtName = "";
if (slaveFilePath.contains(".")) {
slaveFileExtName = slaveFilePath.substring(slaveFilePath.lastIndexOf(".") + 1);
} else {
logger.warn("Fail to upload file, because the format of filename is illegal.");
return slaveFileId;
}
//建立连接
/*.......*/
//上传文件
try {
slaveFileId = client.upload_file1(masterFileId, prefixName, slaveFilePath, slaveFileExtName, null);
} catch (Exception e) {
logger.warn("Upload file \"" + slaveFilePath + "\"fails");
}finally{
trackerServer.close();
}
return slaveFileId;
}
public static int download(String fileId, String localFile) throws Exception{
int result = 0;
//建立连接
TrackerClient tracker = new TrackerClient();
TrackerServer trackerServer = tracker.getConnection();
StorageServer storageServer = null;
StorageClient1 client = new StorageClient1(trackerServer, storageServer);
//上传文件
try {
result = client.download_file1(fileId, localFile);
} catch (Exception e) {
logger.warn("Download file \"" + localFile + "\"fails");
}finally{
trackerServer.close();
}
return result;
}
public static void main(String[] args) {
try {
String masterFileId = uploadFile("D:/Tmp/apk/t01134ede0e696735e7.png");
System.out.println(masterFileId);
download(masterFileId, "D:/Tmp/apk/master.png");
String slaveFileId = uploadSlaveFile(masterFileId, "_120x120", "D:/Tmp/apk/PC.png");
System.out.println(slaveFileId);
download(slaveFileId, "D:/Tmp/apk/slave.png");
} catch (Exception e) {
logger.error("upload file to FastDFS failed.", e);
}
}
}