使用java操作FastDFS上传,下载,删除文件

经过我的测试,直接把代码copy就能用了!

前提条件:将源码生成为jar包,install到本地maven仓库
1.从github上down下源代码:https://github.com/happyfish100/fastdfs-client-java在myeclipse中创建maven项目,然后把解压的内容复制到maven项目中

2.你也可以直接下载我整的maven工程,解压导入myeclipse中直接使用,下载地址:http://download.csdn.net/detail/qq_34021712/9812335
执行maven install 将代码打成jar到本地maven仓库

在maven中依赖jar包

<!-- fastdfs上传下载图片  路径和上面的pom中对应 -->
<dependency>
    <groupId>org.csource.fastdfs-client-java</groupId>
    <artifactId>fastdfs-client-java</artifactId>
    <version>1.25</version>
</dependency>


创建FastDFSClient类

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
 
 
import org.csource.common.MyException;
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.TrackerServer;
 
 
public class FastDFSClient {
 
 
    private  TrackerClient trackerClient = null;
    private  TrackerServer trackerServer = null;
    private  StorageServer storageServer = null;
    private  StorageClient1 storageClient = null;
    
    public FastDFSClient(String conf) throws Exception {
        if (conf.contains("classpath:")) {
            String path = URLDecoder.decode(getClass().getProtectionDomain().getCodeSource().getLocation().toString(),"UTF-8"); 
            path=path.substring(6);
            conf = conf.replace("classpath:",URLDecoder.decode(path,"UTF-8"));
        }
        ClientGlobal.init(conf);
        trackerClient = new TrackerClient();
        trackerServer = trackerClient.getConnection();
        storageServer = null;
        storageClient = new StorageClient1(trackerServer, storageServer);
    }
    
    /**
     * 上传文件方法
     * <p>Title: uploadFile</p>
     * <p>Description: </p>
     * @param fileName 文件全路径
     * @param extName 文件扩展名,不包含(.)
     * @param metas 文件扩展信息
     * @return
     * @throws Exception
     */
    public String uploadFile(String fileName, String extName, NameValuePair[] metas) {
        String result=null;
        try {
            result = storageClient.upload_file1(fileName, extName, metas);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
        return result;
    }
    
    /**
     * 上传文件,传fileName
     * @param fileName 文件的磁盘路径名称 如:D:/image/aaa.jpg
     * @return null为失败
     */
    public String uploadFile(String fileName) {
        return uploadFile(fileName, null, null);
    }
    /**
     * 
     * @param fileName 文件的磁盘路径名称 如:D:/image/aaa.jpg
     * @param extName 文件的扩展名 如 txt jpg等
     * @return null为失败
     */
    public  String uploadFile(String fileName, String extName) {
        return uploadFile(fileName, extName, null);
    }
    
    /**
     * 上传文件方法
     * <p>Title: uploadFile</p>
     * <p>Description: </p>
     * @param fileContent 文件的内容,字节数组
     * @param extName 文件扩展名
     * @param metas 文件扩展信息
     * @return
     * @throws Exception
     */
    public String uploadFile(byte[] fileContent, String extName, NameValuePair[] metas) {
        String result=null;
        try {
            result = storageClient.upload_file1(fileContent, extName, metas);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 上传文件
     * @param fileContent 文件的字节数组
     * @return null为失败
     * @throws Exception
     */
    public String uploadFile(byte[] fileContent) throws Exception {
        return uploadFile(fileContent, null, null);
    }
    
    /**
     * 上传文件
     * @param fileContent  文件的字节数组
     * @param extName  文件的扩展名 如 txt  jpg png 等
     * @return null为失败
     */
    public String uploadFile(byte[] fileContent, String extName) {
        return uploadFile(fileContent, extName, null);
    }
    
    /**
     * 文件下载到磁盘
     * @param path 图片路径
     * @param output 输出流 中包含要输出到磁盘的路径
     * @return -1失败,0成功
     */
    public int download_file(String path,BufferedOutputStream output) {
        //byte[] b = storageClient.download_file(group, path);
        int result=-1;
        try {
            byte[] b = storageClient.download_file1(path);
                try{
                    if(b != null){
                        output.write(b);
                        result=0;
                    }
                }catch (Exception e){} //用户可能取消了下载
                finally {
                    if (output != null)
                        try {
                            output.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 获取文件数组
     * @param path 文件的路径 如group1/M00/00/00/wKgRsVjtwpSAXGwkAAAweEAzRjw471.jpg
     * @return
     */
    public byte[] download_bytes(String path) {
        byte[] b=null;
        try {
            b = storageClient.download_file1(path);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
        return b;
    }
    
    /**
     * 删除文件
     * @param group 组名 如:group1
     * @param storagePath 不带组名的路径名称 如:M00/00/00/wKgRsVjtwpSAXGwkAAAweEAzRjw471.jpg
     * @return -1失败,0成功
     */
    public Integer delete_file(String group ,String storagePath){
        int result=-1;
        try {
            result = storageClient.delete_file(group, storagePath);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
         return  result;
    }
    /**
     * 
     * @param storagePath  文件的全部路径 如:group1/M00/00/00/wKgRsVjtwpSAXGwkAAAweEAzRjw471.jpg
     * @return -1失败,0成功
     * @throws IOException
     * @throws Exception
     */
    public Integer delete_file(String storagePath){
        int result=-1;
        try {
            result = storageClient.delete_file1(storagePath);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
        return  result;
    }
}


创建Test测试类

package com.taotao.controller;
 
import java.util.List;
 
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taotao.common.util.FastDFSClient;
import com.taotao.mapper.TbItemMapper;
import com.taotao.pojo.TbItem;
import com.taotao.pojo.TbItemExample;
 
public class Test {
    
    /*@org.junit.Test
    public void testPageHelper(){
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext-*.xml");
        TbItemMapper tbItemMapper = applicationContext.getBean(TbItemMapper.class);
        //执行查询,并分页
                TbItemExample example = new TbItemExample();
                //分页处理
                PageHelper.startPage(2, 10);
                List<TbItem> list = tbItemMapper.selectByExample(example);
                //取商品列表
                for (TbItem tbItem : list) {
                    System.out.println(tbItem.getTitle());
                }
                //取分页信息
                PageInfo<TbItem> pageInfo = new PageInfo<>(list);
                long total = pageInfo.getTotal();
                System.out.println("共有商品:"+ total);
    }
    
    @org.junit.Test
    public void testUpload() throws Exception {
        // 1、把FastDFS提供的jar包添加到工程中
                // 2、初始化全局配置。加载一个配置文件。
                ClientGlobal.init("D:\\MyEclipse2\\taotao-manager\\taotao-manager-web\\src\\main\\resources\\properties\\fastdfs-client.conf");
                // 3、创建一个TrackerClient对象。
                TrackerClient trackerClient = new TrackerClient();
                // 4、创建一个TrackerServer对象。
                TrackerServer trackerServer = trackerClient.getConnection();
                // 5、声明一个StorageServer对象,null。
                StorageServer storageServer = null;
                // 6、获得StorageClient对象。
                StorageClient storageClient = new StorageClient(trackerServer, storageServer);
                // 7、直接调用StorageClient对象方法上传文件即可。
                String[] strings = storageClient.upload_file("D:\\image\\aaa.jpg", "jpg", null);
                for (String string : strings) {
                    System.out.println(string);
                }
    }*/
    
    /**
     * 测试上传
     * @throws Exception
     */
    @org.junit.Test
    public void testFastDfsClient() throws Exception {
        FastDFSClient client = new FastDFSClient("D:\\MyEclipse2\\taotao-manager\\taotao-manager-web\\src\\main\\resources\\properties\\fastdfs-client.conf");
        String uploadFile = client.uploadFile("D:\\image\\aaa.jpg", "jpg");
        System.out.println(uploadFile);
    }
    /**
     * 测试删除
     * @throws Exception
     */
    @org.junit.Test
    public void testFastDfsClientDelete() throws Exception {
        FastDFSClient client = new FastDFSClient("D:\\MyEclipse2\\taotao-manager\\taotao-manager-web\\src\\main\\resources\\properties\\fastdfs-client.conf");
        //String uploadFile = client.uploadFile("D:\\image\\aaa.jpg", "jpg");
        //Integer delete_file = client.delete_file("group1","M00/00/00/wKgRsVjtwg-ACOlSAAAweEAzRjw844.jpg");
        Integer delete_file = client.delete_file("group1/M00/00/00/wKgRsVjtyWqAdpG9AAAweEAzRjw047.jpg");
        System.out.println(delete_file);
    }
    
 
}

原文链接:https://blog.csdn.net/qq_34021712/article/details/70149604?utm_source=blogxgwz0

猜你喜欢

转载自blog.csdn.net/qq_36688143/article/details/84229119
今日推荐