天天看點

FastDFS學習筆記(三)Java API調用 本例完成代碼下載下傳1、下載下傳fastdfs-client-java到本地,2、建立測試應用3、Java本地連接配接需要伺服器開啟的端口4、踩過的坑

概覽:

1、下載下傳https://github.com/happyfish100/fastdfs-client-java到本地,mvn install 部署到本地倉庫,供應用系統引用jar包

2、應用系統引入jar包,并編寫工具類,測試代碼

 本例完成代碼下載下傳

1、下載下傳fastdfs-client-java到本地,

導入本地,執行mvn install 部署到本地倉庫

FastDFS學習筆記(三)Java API調用 本例完成代碼下載下傳1、下載下傳fastdfs-client-java到本地,2、建立測試應用3、Java本地連接配接需要伺服器開啟的端口4、踩過的坑

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

解決方法:重新開機了一下伺服器好了

 本例完成代碼下載下傳

繼續閱讀