需要先安裝好fastdfs服務,參考安裝介紹
集成java客戶端
1、下載客戶端源碼
git clone https://github.com/happyfish100/fastdfs-client-java.git
打開工程,自己在本地打包 mvn:install
2、在pom中增加客戶端依賴
<dependency>
<groupId>org.csource</groupId>
<artifactId>fastdfs-client-java</artifactId>
<version>1.27-SNAPSHOT</version>
</dependency>
配置
1、在配置文件中添加配置項
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.41:22122
2、創建屬性配置類FdfsConfig
@Data
@Component
@ConfigurationProperties(prefix = "fastdfs")
public class FdfsConfig {
private int connectTimeoutInSeconds;
private int networkTimeoutInSeconds;
private String charset;
private boolean httpAntiStealToken;
private String httpSecretKey;
private int httpTrackerHttpPort;
private String trackerServers;
public Properties getProperties() {
Properties properties =new Properties();
properties.put(ClientGlobal.PROP_KEY_TRACKER_SERVERS, trackerServers);
properties.put(ClientGlobal.PROP_KEY_HTTP_TRACKER_HTTP_PORT, httpTrackerHttpPort);
properties.put(ClientGlobal.PROP_KEY_HTTP_SECRET_KEY, httpSecretKey);
properties.put(ClientGlobal.PROP_KEY_HTTP_ANTI_STEAL_TOKEN, httpAntiStealToken);
properties.put(ClientGlobal.PROP_KEY_CHARSET, charset);
properties.put(ClientGlobal.PROP_KEY_NETWORK_TIMEOUT_IN_SECONDS, networkTimeoutInSeconds);
properties.put(ClientGlobal.PROP_KEY_CONNECT_TIMEOUT_IN_SECONDS, connectTimeoutInSeconds);
return properties;
}
}
3、在service中使用完整代碼示例
@Bean
public FileManageFdfsImpl fileManageFdfsImpl() {
return new FileManageFdfsImpl();
}
public class FileManageFdfsImpl implements IFileManage {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private FdfsConfig config;
private TrackerClient trackerClient;
@PostConstruct
public void initStorageClient() throws Exception {
Properties prop = config.getProperties();
ClientGlobal.initByProperties(prop);
logger.info("network_timeout=" + ClientGlobal.g_network_timeout + "ms");
logger.info("charset=" + ClientGlobal.g_charset);
trackerClient = new TrackerClient();
}
private void closeTrackerServer(TrackerServer trackerServer) {
try {
if (trackerServer != null) {
trackerServer.close();
}
} catch (IOException e) {
logger.error("error", e);
}
}
/** 上傳文件到fastdfs */
public void upload(InputStream input, SysFile sysFile, boolean isSmallPic) throws Exception {
TrackerServer trackerServer = trackerClient.getConnection();
StorageClient storageClient = new StorageClient(trackerServer, null);
try {
int length = input.available();
byte[] bytes = new byte[length];
input.read(bytes);
NameValuePair[] metaList = new NameValuePair[1];
metaList[0] = new NameValuePair("fileName", sysFile.getOriginalFilename());
String[] result;
if (isSmallPic) {
result = storageClient.upload_file(sysFile.getBucketName(), bytes, null, metaList);
} else {
result = storageClient.upload_file(bytes, null, metaList);
}
input.close();
logger.info("文件大小:" + bytes.length + " 字節");
String group = null;
String filePath = null;
if (result != null && result.length == 2) {
group = result[0];
filePath = result[1];
} else {
throw new ApplicationException("附件上傳失敗:" + result);
}
sysFile.setBucketName(group);
if (isSmallPic) {
sysFile.setSmallPicKey(filePath);
} else {
sysFile.setFileKey(filePath);
}
} finally {
closeTrackerServer(trackerServer);
}
}
/** 文件下載 */
public InputStream download(SysFile sysFile, boolean isSmallPic) throws Exception {
TrackerServer trackerServer = trackerClient.getConnection();
StorageClient storageClient = new StorageClient(trackerServer, null);
try {
String fileKey = sysFile.getFileKey();
if (isSmallPic && StringUtils.isNotBlank(sysFile.getSmallPicKey())) {
fileKey = sysFile.getSmallPicKey();
}
byte[] result = storageClient.download_file(sysFile.getBucketName(), fileKey);
return new ByteArrayInputStream(result);
} finally {
storageClient.close();
closeTrackerServer(trackerServer);
}
}
/** 文件刪除 */
public void delete(SysFile sysFile) throws Exception {
TrackerServer trackerServer = trackerClient.getConnection();
StorageClient storageClient = new StorageClient(trackerServer, null);
try {
storageClient.delete_file(sysFile.getBucketName(), sysFile.getFileKey());
if (StringUtils.isNotBlank(sysFile.getSmallPicKey())) {
storageClient.delete_file(sysFile.getBucketName(), sysFile.getSmallPicKey());
}
} finally {
closeTrackerServer(trackerServer);
}
}
}
單獨上傳/下載/刪除示例
1、上傳
@Test
public void upload() throws Exception{
NameValuePair[] metaList = new NameValuePair[1];
String local_filename = "dl_erweim1a.png";
metaList[0] = new NameValuePair("fileName", local_filename);
File file = new File("D:/dl_erweim1a.png");
InputStream inputStream = new FileInputStream(file);
int length = inputStream.available();
byte[] bytes = new byte[length];
inputStream.read(bytes);
String[] result = storageClient.upload_file(bytes, null, metaList);
System.out.println( Arrays.asList(result));
// LOGGER.info("result {}", Arrays.asList(result));
Assert.assertEquals(2, result.length);
}
上傳成功後,返回String[]數組,分別是group和filePath
在文件下載/刪除時,也是傳入這兩個參數
2、下載
@Test
public void download() throws Exception {
String[] uploadresult = {"group1", "M00/00/00/wKgBKV2NzQSAPCAsAAA-QqOY9ks2727402"};
byte[] result = storageClient.download_file(uploadresult[0], uploadresult[1]);
String local_filename = "d:/build.PNG";
writeByteToFile(result, local_filename);
File file = new File(local_filename);
Assert.assertTrue(file.isFile());
}
3、刪除
@Test
public void delete() throws Exception {
String[] uploadresult = {"group1", "M00/00/00/wKgBKV2NzQSAPCAsAAA-QqOY9ks2727402"};
int result = storageClient.delete_file(uploadresult[0], uploadresult[1]);
System.out.println(result);
// Assert.assertTrue(result == 0);
}
返回0代表刪除成功
參考
https://github.com/happyfish100/fastdfs-client-java