FastDFS学习笔记(三)Java API调用

概览:

1、下载https://github.com/happyfish100/fastdfs-client-java到本地,mvn install 部署到本地仓库,供应用系统引用jar包

2、应用系统引入jar包,并编写工具类,测试代码

 本例完成代码下载

1、下载fastdfs-client-java到本地,

导入本地,执行mvn install 部署到本地仓库

2、创建测试应用

2.1、创建springboot应用,引入fastdfs-client-java

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

2.2、src/main/resources目录下新增fdfs_client.properties文件

connect_timeout =2
network_timeout =30
charset=UTF-8
# tracker Http端口
http.tracker_http_port=6666
# 暂无作用
http.anti_steal_token=no
# 暂无作用
http.secret_key=FastDFS1234567890
# tracker Server地址信息
tracker_server=192.168.0.89:22122

2.3、编写工具类

package com.zzstxx;

import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.URLDecoder;

/**
 * FastDFS工具类【实现文件上传、下载、删除、查询】
 * @author 
 */
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) {
        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;
    }

    /**
     * 获取远程服务器文件资源信息
     * @param groupName   文件组名 如:group1
     * @param remoteFileName M00/00/00/wKgRsVjtwpSAXGwkAAAweEAzRjw471.jpg
     * @return
     */
    public FileInfo getFile(String groupName,String remoteFileName){
        try {
            return storageClient.get_file_info(groupName, remoteFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 获取远程服务器文件资源信息
     * @param file_id group1/M00/00/00/wKgRsVjtwpSAXGwkAAAweEAzRjw471.jpg
     * @return
     */
    public FileInfo getFile1(String file_id){
        try {
        	
            return storageClient.get_file_info1(file_id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 获取附件参数
     * @param groupName   文件组名 如:group1
     * @param remoteFileName M00/00/00/wKgRsVjtwpSAXGwkAAAweEAzRjw471.jpg
     * @return
     */
    public NameValuePair[] getMetadata(String groupName,String remoteFileName){
        try {
            return storageClient.get_metadata(groupName, remoteFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 获取附件参数
     * @param path file_id group1/M00/00/00/wKgRsVjtwpSAXGwkAAAweEAzRjw471.jpg
     * @return
     */
    public NameValuePair[] getMetadataByFileId(String file_id){
        try {
            return storageClient.get_metadata1(file_id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

3、编写测试类

package com.zzstxx;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.FileInfo;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class FastDFSController {

	private String CONF_FILENAME = "fdfs_client.properties";

	/**
	 * 上传文件
	 * 
	 * @param request
	 * @throws Exception
	 */
	@RequestMapping(value = "file/uploadFast", method = RequestMethod.GET)
	public void uploadFast(HttpServletRequest request) throws Exception {
		// 1、把FastDFS提供的jar包添加到工程中
		// 2、初始化全局配置。加载一个配置文件。
		String confUrl = this.getClass().getClassLoader().getResource(this.CONF_FILENAME).getPath();
		FastDFSClient fastDFSClient = new FastDFSClient(confUrl);
		// 上传文件
		String filePath = fastDFSClient.uploadFile("g:\\1.exe");
		System.out.println("返回路径:" + filePath);
	}

	/**
	 * 上传文件(带参数)
	 * 
	 * @param request
	 * @throws Exception
	 */
	@RequestMapping(value = "file/uploadFast1", method = RequestMethod.GET)
	public void uploadFast1(HttpServletRequest request) throws Exception {
		String confUrl = this.getClass().getClassLoader().getResource(this.CONF_FILENAME).getPath();
		FastDFSClient fastDFSClient = new FastDFSClient(confUrl);
		// 组合参数
		NameValuePair nvp[] = new NameValuePair[] { new NameValuePair("fileName", "1.zip"),
				new NameValuePair("fileTtype", "zip") };
		// 上传文件
		String filePath = fastDFSClient.uploadFile("g:\\1.zip", null, nvp);
		System.out.println("返回路径:" + filePath);
	}

	/**
	 * 获取上传附件的参数
	 * 
	 * @param request
	 * @throws Exception
	 */
	@RequestMapping(value = "file/getMetadata", method = RequestMethod.GET)
	public void getMetadata(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String fileId = "group1/M00/00/00/wKgAWV3Bg9OAAEAGAWRtDEpCZww835.zip";
		String confUrl = this.getClass().getClassLoader().getResource(this.CONF_FILENAME).getPath();
		FastDFSClient fastDFSClient = new FastDFSClient(confUrl);
		NameValuePair nvps[] = fastDFSClient.getMetadataByFileId(fileId);
		if (null != nvps && nvps.length > 0) {
			for (NameValuePair nvp : nvps) {
				System.out.println(nvp.getName() + ":" + nvp.getValue());
			}
		}
	}

	/**
	 * 获取上传附件的参数
	 * 
	 * @param request
	 * @throws Exception
	 */
	@RequestMapping(value = "file/getFileInfo", method = RequestMethod.GET)
	public void getFileInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String fileId = "group1/M00/00/00/wKgAWV3Bg9OAAEAGAWRtDEpCZww835.zip";
		String confUrl = this.getClass().getClassLoader().getResource(this.CONF_FILENAME).getPath();
		FastDFSClient fastDFSClient = new FastDFSClient(confUrl);
		FileInfo fileInfo = fastDFSClient.getFile1(fileId);
		System.out.println("文件大小:"+fileInfo.getFileSize());
		System.out.println("文件创建日期:"+fileInfo.getCreateTimestamp());
		System.out.println("附件来源IP:"+fileInfo.getSourceIpAddr());
	}

	/**
	 * 下载附件
	 * 
	 * @param request
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	@RequestMapping(value = "file/downloadFast", method = RequestMethod.GET)
	public void downloadFast(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String fileId = "group1/M00/00/00/wKgAWV3Bg9OAAEAGAWRtDEpCZww835.zip";
		String confUrl = this.getClass().getClassLoader().getResource(this.CONF_FILENAME).getPath();
		FastDFSClient fastDFSClient = new FastDFSClient(confUrl);
		String filePath = request.getRealPath("/") + "aa.zip";
		int downFlag = fastDFSClient.download_file(fileId, new BufferedOutputStream(new FileOutputStream(filePath)));
		this.outPut(response, filePath, null);
		System.out.println("下载结果为:" + (downFlag == 0 ? "下载文件成功" : "下载文件失败"));
	}

	/**
	 * 输出流
	 * 
	 * @param response
	 * @param filepath
	 */
	public void outPut(HttpServletResponse response, String filepath, String name) {
		try {
			File file = new File(filepath);
			if (!file.exists())
				return;
			String filename = file.getName();
			if (StringUtils.isEmpty(name)) {
				name = filename;
			}
			String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
			InputStream fis = new BufferedInputStream(new FileInputStream(filepath));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			response.reset();
			response.addHeader("Content-Length", "" + file.length());
			response.addHeader("Content-Disposition",
					"attachment; filename=" + new String(name.getBytes("GBK"), "ISO8859-1"));// 解决在弹出文件下载框不能打开文件的问题
			response.setContentLength((int) file.length());
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			if (ext.equals("xls")) {
				response.setContentType("application/msexcel");
			} else {
				response.setContentType("application/octet-stream;charset=GBK");
			}
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

}

3、Java本地连接需要服务器开启的端口

tracker的端口22122:/etc/fdfs/storage.conf 的tracker_server=192.168.0.89:22122

storage的端口23000:/etc/fdfs/storage.conf 的port=23000

4、踩过的坑

异常处理:

fastdfs 上传大文件  Connection reset by peer: socket write error

解决方法:重启了一下服务器好了

 本例完成代码下载

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值