上次文件到FastDFS步骤

spring boot项目下添加FastDFS

首先在pom.xml中加入

        
            commons-fileupload
            commons-fileupload
            1.3.3
        
        

这个jar是需要自己加入的
        
            com.github.tobato
            fastdfs-client
            1.26.1-RELEASE
        

获取fastdfs-client自定义jar包

链接:https://pan.baidu.com/s/13arvtucGnQFqZ5lBSpJV1A 提取码:2gn3

 

fast工厂类

package com.sms.tenantexamineserver.io;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.springframework.core.io.ClassPathResource;

import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 客户端工厂类
 * @author Administrator
 */
public class FastDFSFactory {
	
	private static Logger log= LogManager.getLogger(FastDFSFactory.class);
	
	/**
	 * 创建存储客户端对象
	 */
	private static FastDFSFactory fastDFSFactory=new FastDFSFactory();
	
	private String fdfsConfigFilename="fdfs_client.conf";
	private StorageClient storageClient = null;
	
	private FastDFSFactory(){
		ClassPathResource classPathResource = new ClassPathResource(fdfsConfigFilename);
		String path="";
		try {
			path = classPathResource.getFile().getPath();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		try {
			ClientGlobal.init(path);
			TrackerClient tracker = new TrackerClient();
			TrackerServer trackerServer = tracker.getConnection();
			StorageServer storageServer = tracker.getStoreStorage(trackerServer);
	  		if (storageServer == null) {
	  			log.error("getStoreStorage fail, error code: " + tracker.getErrorCode());
	  		}
	  		storageClient = new StorageClient(trackerServer, storageServer);
		} catch (FileNotFoundException e) {
			log.error(e);
		} catch (IOException e) {
			log.error(e);
		} catch (MyException e) {
			log.error(e);
		}
	}
	
	public static FastDFSFactory getInstance() {
		return fastDFSFactory;
	}

	public StorageClient getStorageClient() {
		return storageClient;
	}

	public void setStorageClient(StorageClient storageClient) {
		this.storageClient = storageClient;
	}
	
}

接口层

package com.sms.tenantexamineserver.io;

import java.io.File;
import java.io.InputStream;

public interface FilePersistence {

	String[] uploadFile(String fileName, String extName, String[] meta_list) throws Exception;
	
	String[] uploadFile(byte[] fileBuff, String fileName, String extName, String[] meta_list) throws Exception;
	
	String[] uploadFile(File file, String fileName, String extName, String[] meta_list) throws Exception;
	
	InputStream downloadFile(String path, String filename) throws Exception;

	byte[] downloadByte(String path, String filename) throws Exception;

	byte[] downloadByte(String path, String filename, long fileOffset, long downloadBytes) throws Exception;

	boolean deleteFile(String path, String filename) throws Exception;
	
	String[] modifyFile(String groupName, String remoteFileName, String fileName, String extName, String[] meta_list) throws Exception;
	
	String[] modifyFile(String groupName, String remoteFileName, byte[] fileBuff, String fileName, String extName, String[] meta_list) throws Exception;
	
	String[] modifyFile(String groupName, String remoteFileName, File file, String fileName, String extName, String[] meta_list) throws Exception;
	
	boolean checkFile(String path, String filename);
}

实现类,客户端层

package com.sms.tenantexamineserver.io;

import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.StorageClient;
import org.springframework.stereotype.Component;

import java.io.*;

/**
 * FastDFS客户端类
 * @author Administrator
 */
@Component
public class FastDFSClient implements FilePersistence {

	/**
	 * 根据本地文件名上传
	 * @Create_by:xiedan
	 * @param fileName 本地文件名,包含全路径和扩展名
	 * @param extName  文件扩展名
	 * @param meta_list 元数据,可为空
	 * @return string[0] groupName 分组名, string[1] remoteFileName 服务器存储文件名
	 * @throws Exception
	 */
	@Override
	public String[] uploadFile(String fileName, String extName,
			String[] meta_list) throws Exception {
		StorageClient storageClient = FastDFSFactory.getInstance().getStorageClient();
		NameValuePair[] nameValuePairs = getNameValuePair(meta_list);
		return storageClient.upload_file(fileName, extName, nameValuePairs);
	}

	
	/**
	 * 根据字节流上传
	 * @Create_by:xiedan
	 * @param fileBuff 上传文件字节流
	 * @param extName  文件扩展名
	 * @param meta_list 元数据,可为空
	 * @return
	 * @throws Exception
	 */
	@Override
	public String[] uploadFile(byte[] fileBuff,String fileName, String extName,
			String[] meta_list) throws Exception {
		StorageClient storageClient = FastDFSFactory.getInstance().getStorageClient();
		NameValuePair[] nameValuePairs = getNameValuePair(meta_list);
		return storageClient.upload_file(fileBuff, extName, nameValuePairs);
	}
	
	/**
	 * 根据File对象上传
	 * @Create_by:xiedan
	 * @param file File对象
	 * @param extName  文件扩展名
	 * @param meta_list 元数据,可为空
	 * @return
	 * @throws Exception
	 */
	@Override
	public String[] uploadFile(File file,String fileName, String extName, String[] meta_list) throws Exception {
		StorageClient storageClient = FastDFSFactory.getInstance().getStorageClient();
		InputStream fis = new FileInputStream(file);
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] fileBuff = new byte[(int) file.length()];
		fis.read(fileBuff);
		bos.write(fileBuff);
		fis.close();
		bos.close();
		NameValuePair[] nameValuePairs = getNameValuePair(meta_list);
		return storageClient.upload_file(fileBuff, extName, nameValuePairs);
	}
	
	/**
	 * 下载文件
	 * @Create_by:xiedan
	 * @param groupName 组名,上传时服务器返回
	 * @param remoteFileName 远程文件名,上传时服务器返回
	 * @return byte[] 下载文件字节流
	 * @throws MyException 
	 * @throws Exception 
	 */
	@Override
	public InputStream downloadFile(String groupName,String remoteFileName) throws Exception {
		return new ByteArrayInputStream(downloadByte(groupName,remoteFileName));
	}

	@Override
	public byte[] downloadByte(String groupName, String remoteFileName) throws Exception {
	    return downloadByte(groupName,remoteFileName,0,0);
	}

    @Override
    public byte[] downloadByte(String groupName, String remoteFileName, long fileOffset, long downloadBytes) throws Exception {
        StorageClient storageClient = FastDFSFactory.getInstance().getStorageClient();
        byte[] data = storageClient.download_file(groupName, remoteFileName,fileOffset,downloadBytes);
        return data;
    }

    /**
	 * 删除文件
	 * @Create_by:xiedan
	 * @param groupName
	 * @param remoteFileName
	 * @return 返回0表示成功
	 * @throws Exception
	 */
	@Override
	public boolean deleteFile(String groupName, String remoteFileName) throws Exception {
		StorageClient storageClient = FastDFSFactory.getInstance().getStorageClient();
		return storageClient.delete_file(groupName, remoteFileName)==0?true:false;
	}
	
	/**
	 * 修改文件
	 * @Create_by:xiedan
	 * @param groupName
	 * @param remoteFileName
	 * @param fileName
	 * @param extName
	 * @param meta_list
	 * @return string[0] groupName 分组名, string[1] remoteFileName 服务器存储文件名
	 * @throws Exception
	 */
	@Override
	public String[] modifyFile(String groupName, String remoteFileName, 
			String fileName,String extName,String[] meta_list) throws Exception {
		StorageClient storageClient = FastDFSFactory.getInstance().getStorageClient();
		storageClient.delete_file(groupName, remoteFileName);
		NameValuePair[] nameValuePairs = getNameValuePair(meta_list);
		return storageClient.upload_file(fileName, extName, nameValuePairs);
	}

	/**
	 * 修改文件
	 * @Create_by:xiedan
	 * @param groupName
	 * @param remoteFileName
	 * @param fileName
	 * @param extName
	 * @param meta_list
	 * @return string[0] groupName 分组名, string[1] remoteFileName 服务器存储文件名
	 * @throws Exception
	 */
	@Override
	public String[] modifyFile(String groupName, String remoteFileName,
			byte[] fileBuff,String fileName, String extName, String[] meta_list) throws Exception {
		StorageClient storageClient = FastDFSFactory.getInstance().getStorageClient();
		storageClient.delete_file(groupName, remoteFileName);
		return this.uploadFile(fileBuff,fileName, extName, meta_list);
	}

	/**
	 * 修改文件
	 * @Create_by:xiedan
	 * @param groupName
	 * @param remoteFileName
	 * @param fileName
	 * @param extName
	 * @param meta_list
	 * @return string[0] groupName 分组名, string[1] remoteFileName 服务器存储文件名
	 * @throws Exception
	 */
	@Override
	public String[] modifyFile(String groupName, String remoteFileName,
			File file,String fileName, String extName, String[] meta_list) throws Exception {
		StorageClient storageClient = FastDFSFactory.getInstance().getStorageClient();
		storageClient.delete_file(groupName, remoteFileName);
		return this.uploadFile(file,fileName, extName, meta_list);
	}
	
	private NameValuePair[] getNameValuePair(String[] meta_list){
		NameValuePair[] nameValuePairs = null;
		if(null!=meta_list && meta_list.length>0){
			nameValuePairs=new NameValuePair[meta_list.length];
			for(int i=0,length=meta_list.length;i

以上三个类放在主类能扫描到的包下 

 

fdfs_client.conf在resources目录下和application.xml在一个文件下fdfs_client.conf名称注意在工厂类中对应fdfsConfigFilename获取参数

connect_timeout=30
network_timeout=60
base_path=/fdfs/client
tracker_server=192.168.1.216:22122
log_level=info
use_connection_pool = false
connection_pool_max_idle_time = 3600
load_fdfs_parameters_from_tracker=false
use_storage_id = false
storage_ids_filename = storage_ids.conf
http.tracker_server_port=80

客户端调用

@ApiOperation(value = "ceshi")
    @PostMapping("/TEST")
    public ResultMessage TestDfs(@RequestParam MultipartFile file){
        try{
            String filename = file.getOriginalFilename();//获取提交文件名称
            int index = filename.lastIndexOf(".");
            String[] test = null;
            String extName = filename.substring(index);//获取提交文件后缀名称(jpg)
            String [] fileSixe =  fastDFSClient.uploadFile(file.getBytes(),filename,extName,test);//上传
//返回两个String用来下载文件

            byte[] by = fastDFSClient.downloadByte(fileSixe[0], fileSixe[1]);//下载
            String path = "E:/2019";
            File fi = new File(path);
            if (!fi.exists()){
                fi.mkdirs();
            }
            OutputStream out = new FileOutputStream(new File("E:\\"+path+filename));
            out.write(by);
            out.flush();
            return ResultMessage.Success("chenggong" );
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultMessage.Success("shibai" );
    }

 

你可能感兴趣的:(fastDFS)