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
{
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);
}
}
}