当前位置:网站首页>[utils] fastdfs tool class
[utils] fastdfs tool class
2022-07-28 14:10:00 【One duck, one duck】
One 、 Import dependence
<dependencies>
<dependency>
<groupId>cn.bestwu</groupId>
<artifactId>fastdfs-client-java</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
</dependencies>
Two 、resources Create profile under
fdfs_client.conf
connect_timeout = 10
network_timeout = 30
charset = UTF-8
http.tracker_http_port = 8888
tracker_server = 192.168.40.21:22122
3、 ... and 、 Tool class
package com.ego.commons.utils;
import org.apache.commons.lang3.StringUtils;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import java.io.*;
public class FastDFSClient {
//private static final String CONF_FILENAME = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "fdfs_client.conf";
// Relative paths
private static final String CONF_FILENAME = "fdfs_client.conf";
private static StorageClient storageClient = null;
/** * Load only once . */
static {
try {
ClientGlobal.init(CONF_FILENAME);
TrackerClient trackerClient = new TrackerClient(ClientGlobal.g_tracker_group);
TrackerServer trackerServer = trackerClient.getConnection();
StorageServer storageServer = trackerClient.getStoreStorage(trackerServer);
storageClient = new StorageClient(trackerServer, storageServer);
} catch (Exception e) {
e.printStackTrace();
}
}
/** * * @param inputStream * Input stream of uploaded files * @param fileName * The original name of the uploaded file * @return */
public static String[] uploadFile(InputStream inputStream, String fileName) {
try {
// Metadata of the file
NameValuePair[] meta_list = new NameValuePair[2];
// The first set of metadata , Original name of the file
meta_list[0] = new NameValuePair("file name", fileName);
// The second set of metadata
meta_list[1] = new NameValuePair("file length", inputStream.available()+"");
// Prepare byte array
byte[] file_buff = null;
if (inputStream != null) {
// Check the length of the file
int len = inputStream.available();
// Create a byte array of corresponding length
file_buff = new byte[len];
// The contents of bytes in the input stream , Read into byte array .
inputStream.read(file_buff);
}
// Upload files . Parameter meaning : The contents of the file to be uploaded ( Pass... Using a byte array ), Type of file uploaded ( Extension ), Metadata
String[] fileids = storageClient.upload_file(file_buff, getFileExt(fileName), meta_list);
return fileids;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
/** * * @param file * file * @param fileName * file name * @return return Null Is a failure */
public static String[] uploadFile(File file, String fileName) {
FileInputStream fis = null;
try {
NameValuePair[] meta_list = null; // new NameValuePair[0];
fis = new FileInputStream(file);
byte[] file_buff = null;
if (fis != null) {
int len = fis.available();
file_buff = new byte[len];
fis.read(file_buff);
}
String[] fileids = storageClient.upload_file(file_buff, getFileExt(fileName), meta_list);
return fileids;
} catch (Exception ex) {
return null;
}finally{
if (fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/** * Delete a file based on the group name and remote file name * * @param groupName * for example "group1" If the value is not specified , The default is group1 * @param remoteFileName * for example "M00/00/00/wKgxgk5HbLvfP86RAAAAChd9X1Y736.jpg" * @return 0 For success , Not 0 For failure , Specific error code */
public static int deleteFile(String groupName, String remoteFileName) {
try {
int result = storageClient.delete_file(groupName == null ? "group1" : groupName, remoteFileName);
return result;
} catch (Exception ex) {
return 0;
}
}
/** * Modify an existing file * * @param oldGroupName * Old group name * @param oldFileName * Old file name * @param file * A new file * @param fileName * New file name * @return If it returns null, it means failure */
public static String[] modifyFile(String oldGroupName, String oldFileName, File file, String fileName) {
String[] fileids = null;
try {
// Upload first
fileids = uploadFile(file, fileName);
if (fileids == null) {
return null;
}
// And then delete
int delResult = deleteFile(oldGroupName, oldFileName);
if (delResult != 0) {
return null;
}
} catch (Exception ex) {
return null;
}
return fileids;
}
/** * File download * * @param groupName Volume name * @param remoteFileName file name * @return Back to a stream */
public static InputStream downloadFile(String groupName, String remoteFileName) {
try {
byte[] bytes = storageClient.download_file(groupName, remoteFileName);
InputStream inputStream = new ByteArrayInputStream(bytes);
return inputStream;
} catch (Exception ex) {
return null;
}
}
public static NameValuePair[] getMetaDate(String groupName, String remoteFileName){
try{
NameValuePair[] nvp = storageClient.get_metadata(groupName, remoteFileName);
return nvp;
}catch(Exception ex){
ex.printStackTrace();
return null;
}
}
/** * Get file suffix ( No point ). * * @return Such as :"jpg" or "". */
private static String getFileExt(String fileName) {
if (StringUtils.isBlank(fileName) || !fileName.contains(".")) {
return "";
} else {
return fileName.substring(fileName.lastIndexOf(".") + 1); // Without the last point
}
}
}
边栏推荐
- R language test sample proportion: use prop The test function performs the single sample proportion test to calculate the confidence interval of the p value of the successful sample proportion in the
- Power amplifier and matching network learning
- Poj3259 wormhole solution
- Long closed period private placement products reappearance industry insiders have different views
- 你真的了解esModule吗
- R language uses dpois function to generate Poisson distribution density data and plot function to visualize Poisson distribution density data
- QT自制软键盘 最完美、最简单、跟自带虚拟键盘一样
- R language Visual scatter diagram, geom using ggrep package_ text_ The repl function avoids overlapping labels between data points (add labels to specific areas of the visual image using the parameter
- 7. Dependency injection
- Qt5 development from introduction to mastery -- the first overview
猜你喜欢

什么是自旋锁 自旋锁是指当一个线程尝试获取某个锁时,如果该锁已被其他线程占用,就一直循环检测锁是否被释放,而不是进入线程挂起或睡眠状态。 /** * 为什么用自旋锁:多个线程对同一个变量

83.(cesium之家)cesium示例如何运行

算法---不同路径(Kotlin)

安全保障基于软件全生命周期-Istio的认证机制

How to play a data mining game entry Edition

30 day question brushing plan (II)

论文研读--Masked Generative Distillation

《机器学习》(周志华) 第6章 支持向量 学习心得 笔记

Security assurance is based on software life cycle - networkpolicy application

作为一个程序员,如何高效的管理时间?
随机推荐
SLAM论文合集
R language uses LM function to build multiple linear regression model, writes regression equation according to model coefficient, and uses conflict function to give 95% confidence interval of regressi
[lvgl events] Application of events on different components (I)
Poj3259 wormhole solution
【LVGL事件(Events)】事件代码
Slam thesis collection
多线程与高并发(三)—— 源码解析 AQS 原理
R language ggplot2 visualization: use the ggviolin function of ggpubr package to visualize violin diagrams, set the palette parameter, and customize the border colors of violin diagrams at different l
Socket类关于TCP字符流编程的理解学习
盘点操作URL中常用的几个高效API
P1797 heavy transportation problem solution
How to effectively conduct the review meeting (Part 1)?
Postgresql14安装及主从配置
Multithreading and high concurrency (III) -- source code analysis AQS principle
了解虚拟列表背后原理,轻松实现虚拟列表
【翻译】盐业公司来Linkerd公司是为了负载平衡,留下来是为了效率、可靠性和性能。...
LeetCode 0142.环形链表 II
Power amplifier and matching network learning
Algorithm --- different paths (kotlin)
R语言因子数据的表格和列联表(交叉表)生成:使用summay函数分析列表查看卡方检验结果判断两个因子变量是否独立(使用卡方检验验证独立性)