FastDFS:Java客户都实现文件的上传、下载、修改、删除

FastDFS:Java客户都实现文件的上传、下载、修改、删除

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>cn.fastdfs.demo</groupId>
  <artifactId>fastDFSdemo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <dependencies>
  	<dependency>
		<groupId>org.csource.fastdfs</groupId>
		<artifactId>fastdfs</artifactId>
		<version>1.2</version>
	</dependency>
   <dependency>
     <groupId>commons-logging</groupId>
     <artifactId>commons-logging</artifactId>
     <version>1.1.3</version>
   </dependency>
	<dependency>
	    <groupId>commons-io</groupId>
	    <artifactId>commons-io</artifactId>
	    <version>2.4</version>
	</dependency>
	<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
	<dependency>
	    <groupId>commons-fileupload</groupId>
	    <artifactId>commons-fileupload</artifactId>
	    <version>1.3</version>
	</dependency>
	<!-- https://mvnrepository.com/artifact/log4j/log4j -->
	<dependency>
	    <groupId>log4j</groupId>
	    <artifactId>log4j</artifactId>
	    <version>1.2.17</version>
	</dependency>
	<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
	<dependency>
	    <groupId>org.apache.commons</groupId>
	    <artifactId>commons-lang3</artifactId>
	    <version>3.3.1</version>
	</dependency>
	<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
	<dependency>
	    <groupId>org.slf4j</groupId>
	    <artifactId>slf4j-api</artifactId>
	    <version>1.5.8</version>
	</dependency>
	<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
	<dependency>
	    <groupId>org.slf4j</groupId>
	    <artifactId>slf4j-log4j12</artifactId>
	    <version>1.5.8</version>
	    <scope>test</scope>
	</dependency>


  </dependencies>
  
  
</project>
fastdfs_client.conf
tracker_server=localhost:22122
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerGroup;
import org.csource.fastdfs.TrackerServer;

public class FastDFSClientUtils {

    private static final String CONF_FILENAME = Thread.currentThread().getContextClassLoader().getResource("fastdfs_client.conf").getPath();

    private static Logger logger = Logger.getLogger(FastDFSClientUtils.class);

    
    private static TrackerClient trackerClient;

    
    //加载文件
    static {
        try {
            ClientGlobal.init(CONF_FILENAME);
            TrackerGroup trackerGroup = ClientGlobal.g_tracker_group;
            trackerClient = new TrackerClient(trackerGroup);
        } catch (Exception e) {
            logger.error(e);
        }
    }
    
    /**
     * <B>方法名称:</B>上传方法<BR>
     * <B>概要说明:</B><BR>
     * @param file 文件
     * @param path 路径
     * @return 上传成功返回id,失败返回null
     */
    public static String upload(File file, String path) {
        TrackerServer trackerServer = null;
        StorageServer storageServer = null;
        StorageClient1 storageClient1 = null;
        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);
            }
            
            trackerServer = trackerClient.getConnection();
            if (trackerServer == null) {
                logger.error("getConnection return null");
            }
            storageServer = trackerClient.getStoreStorage(trackerServer);
            storageClient1 = new StorageClient1(trackerServer, storageServer);
            String fileid = storageClient1.upload_file1(file_buff, getFileExt(path), meta_list);
            
            return fileid;
        } catch (Exception ex) {
            logger.error(ex);
            return null;
        }finally{
            if (fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    logger.error(e);
                }
            }
            if (storageServer != null){
                try {
                    storageServer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (trackerServer != null){
                try {
                    trackerServer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            storageClient1 = null;
        }
    }
    
    /**
     * <B>方法名称:</B>上传方法<BR>
     * <B>概要说明:</B><BR>
     * @param data 数据
     * @param path 路径
     * @return 上传成功返回id,失败返回null
     */
    public static String upload(byte[] data, String extName) {
        TrackerServer trackerServer = null;
        StorageServer storageServer = null;
        StorageClient1 storageClient1 = null;
        try {
            NameValuePair[] meta_list = null; // new NameValuePair[0];
            
            trackerServer = trackerClient.getConnection();
            if (trackerServer == null) {
                logger.error("getConnection return null");
            }
            storageServer = trackerClient.getStoreStorage(trackerServer);
            storageClient1 = new StorageClient1(trackerServer, storageServer);
            String fileid = storageClient1.upload_file1(data, extName, meta_list);
            return fileid;
        } catch (Exception ex) {
            logger.error(ex);
            return null;
        }finally{
            if (storageServer != null){
                try {
                    storageServer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (trackerServer != null){
                try {
                    trackerServer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            storageClient1 = null;
        }
    }

    /**
     * <B>方法名称:</B>下载方法<BR>
     * <B>概要说明:</B>通过文件id进行下载<BR>
     * @param fileId 文件id
     * @return 返回InputStream
     */
    public static InputStream download(String groupName, String fileId) {
        TrackerServer trackerServer = null;
        StorageServer storageServer = null;
        StorageClient1 storageClient1 = null;
        try {
            trackerServer = trackerClient.getConnection();
            if (trackerServer == null) {
                logger.error("getConnection return null");
            }
            storageServer = trackerClient.getStoreStorage(trackerServer, groupName);
            storageClient1 = new StorageClient1(trackerServer, storageServer);
            byte[] bytes = storageClient1.download_file1(fileId);
            InputStream inputStream = new ByteArrayInputStream(bytes);
            return inputStream;
        } catch (Exception ex) {
            logger.error(ex);
            return null;
        } finally {
            if (storageServer != null){
                try {
                    storageServer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (trackerServer != null){
                try {
                    trackerServer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            storageClient1 = null;            
        }
    }

    /**
     * <B>方法名称:</B>删除方法<BR>
     * <B>概要说明:</B>根据id来删除一个文件<BR>
     * @param fileId 文件id
     * @return 删除成功返回0,非0则操作失败,返回错误代码
     */
    public static int delete(String groupName, String fileId) {
        TrackerServer trackerServer = null;
        StorageServer storageServer = null;
        StorageClient1 storageClient1 = null;
        try {
            trackerServer = trackerClient.getConnection();
            if (trackerServer == null) {
                logger.error("getConnection return null");
            }
            storageServer = trackerClient.getStoreStorage(trackerServer, groupName);
            storageClient1 = new StorageClient1(trackerServer, storageServer);
            int result = storageClient1.delete_file1(fileId);
            return result;
        } catch (Exception ex) {
            logger.error(ex);
            return 0;
        } finally {
            if (storageServer != null){
                try {
                    storageServer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (trackerServer != null){
                try {
                    trackerServer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            storageClient1 = null;            
        }
    }

    /**
     * <B>方法名称:</B><BR>
     * <B>概要说明:</B><BR>
     * @param oldFileId 旧文件id 
     * @param file 新文件
     * @param path 新文件路径
     * @return 上传成功返回id,失败返回null
     */
    public static String modify(String oldGroupName, String oldFileId, File file, String path) {
        String fileid = null;
        try {
            // 先上传
            fileid = upload(file, path);
            if (fileid == null) {
                return null;
            }
            // 再删除
            int delResult = delete(oldGroupName, oldFileId);
            if (delResult != 0) {
                return null;
            }
        } catch (Exception ex) {
            logger.error(ex);
            return null;
        }
        return fileid;
    }

    /**
     * <B>方法名称:</B>获取文件后缀名<BR>
     * <B>概要说明:</B>获取文件后缀名<BR>
     * @param fileName
     * @return  如:"jpg"、"txt"、"zip" 等
     */
    private static String getFileExt(String fileName) {
        if (StringUtils.isBlank(fileName) || !fileName.contains(".")) {
            return "";
        } else {
            return fileName.substring(fileName.lastIndexOf(".") + 1); 
        }
    }
}
import java.io.File;
import java.io.InputStream;

import org.apache.commons.io.FileUtils;



public class FastDFSTest {
    
    /**
     * 上传
     */
    public static void upload() throws Exception {
        String path = "C:\\Users\\Leon.sun\\Desktop\\Temp\\img\\56.jpg";
        File file = new File(path);
        String fileId = FastDFSClientUtils.upload(file, path);
        // 本地文件:C:\Users\Leon.sun\Desktop\Temp\img\56.jpg,上传成功! 文件ID为:group1/M00/00/00/rBH2Clw3EpeAbO70AAB5yKpbklA306.jpg
        System.out.println("本地文件:" + path + ",上传成功! 文件ID为:" + fileId);
    }
    
    /**
     * 下载
     */
    public static void download() throws Exception {
        String fileId = "group1/M00/00/00/rBH2Clw3EpeAbO70AAB5yKpbklA306.jpg";
        InputStream inputStream = FastDFSClientUtils.download("group1", fileId);
        System.out.println(inputStream.available());
        String path = "C:\\Users\\Leon.sun\\Desktop\\Temp\\img\\66.jpg";
        System.out.println(path);
        FileUtils.copyInputStreamToFile(inputStream,  new File(path));
    }

    /**
     * 删除
     */
    public static void delete() throws Exception {
        String fileId = "group1/M00/00/00/rBH2Clw3EpeAbO70AAB5yKpbklA306.jpg";
        int result = FastDFSClientUtils.delete("group1", fileId);
        System.out.println(result == 0 ? "删除成功" : "删除失败:" + result);
    }


    
    /**
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
    

//        upload();
//        download();
//        Thread.sleep(10000);
//        download();
//        Thread.sleep(10000);
//        download();
        delete();

    }

}

 

org.csource:fastdfs-client-java:1.29-是一个Java语言的FastDFS客户端,用于访问FastDFS分布式文件系统。FastDFS是一个开源的分布式文件系统,具有高性能、高可靠性、可扩展性和易于管理等特点。FastDFS文件分成许多小块,然后存储在多台服务器上,提供了快速的文件上传下载功能。 org.csource:fastdfs-client-java:1.29-是FastDFSJava语言实现,通过该客户端,我们可以轻松地在Java项目中使用FastDFS进行文件上传下载。它提供了一组简单易用的API,允许我们通过指定文件路径或字节数组来上传文件,并通过文件的标识符来下载文件。同时,我们还可以获取文件的元信息,例如文件大小、创建时间等。 通过该客户端,我们还可以进行文件删除修改和查询等操作。它提供了丰富的接口方法,可以满足不同的业务需求。此外,该客户端还支持文件的断点续传功能,当网络中断或上传下载过程中出现异常时,我们可以恢复中断的操作,避免重新上传下载整个文件。 org.csource:fastdfs-client-java:1.29-是一个成熟稳定的Java组件,被广泛应用于各种基于Java的项目中。它的源代码是开放的,意味着我们可以根据自己的需求进行修改和定制。此外,它还具有良好的文档和社区支持,我们可以在遇到问题时及时获得帮助和解决方案。 总之,org.csource:fastdfs-client-java:1.29-是一个功能强大、易用的Java客户端,提供了丰富的API和功能,帮助我们轻松地在Java项目中使用FastDFS分布式文件系统。它是一个值得信赖和推荐的工具,可以提高文件操作的效率和可靠性。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值