天天看點

10、SpringBoot2.0內建FastDFS(十)

前言:由于本篇部落格是建立在上一個部落格上寫的,是以閱讀本篇部落格之前需要先看下檔案上傳功能的實作

1、引入pom檔案:

<dependency>
    <groupId>org.csource</groupId>
    <artifactId>fastdfs-client-java</artifactId>
    <version>1.27-SNAPSHOT</version>
</dependency>      

有些小夥伴在引入該依賴時可能會報錯,是因為中央倉庫并沒有內建該依賴,需要下載下傳該jar包然後打包到本地倉庫,下載下傳fastdfs-client-java開發工具包:

​​​ https://github.com/happyfish100/fastdfs-client-java​​​ 解壓後cmd進入該檔案下,然後運作下面的Maven指令:

mvn clean install

2、在resources檔案夾下新增fdfs_client.conf檔案:

connect_timeout = 60
network_timeout = 60
charset = UTF-8
http.anti_steal_token = no
http.secret_key = 123456
#FastDFS伺服器的IP位址
tracker_server = 192.168.53.85:22122
tracker_server = 192.168.53.86:22122      

3、新增FastDFS核心類:

FastDFSClient:

package com.xhy.xczx.fastdfs;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

public class FastDFSClient {
  private static org.slf4j.Logger logger = LoggerFactory.getLogger(FastDFSClient.class);

  static {
    try {
      String filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();;
      ClientGlobal.init(filePath);
    } catch (Exception e) {
      logger.error("FastDFS Client Init Fail!",e);
    }
  }

  public static String[] upload(FastDFSFile file) {
    logger.info("File Name: " + file.getName() + "File Length:" + file.getContent().length);

    NameValuePair[] meta_list = new NameValuePair[1];
    meta_list[0] = new NameValuePair("author", file.getAuthor());

    long startTime = System.currentTimeMillis();
    String[] uploadResults = null;
    StorageClient storageClient=null;
    try {
      storageClient = getTrackerClient();
      uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
    } catch (IOException e) {
      logger.error("IO Exception when uploadind the file:" + file.getName(), e);
    } catch (Exception e) {
      logger.error("Non IO Exception when uploadind the file:" + file.getName(), e);
    }
    logger.info("upload_file time used:" + (System.currentTimeMillis() - startTime) + " ms");

    if (uploadResults == null && storageClient!=null) {
      logger.error("upload file fail, error code:" + storageClient.getErrorCode());
    }
    String groupName = uploadResults[0];
    String remoteFileName = uploadResults[1];

    logger.info("upload file successfully!!!" + "group_name:" + groupName + ", remoteFileName:" + " " + remoteFileName);
    return uploadResults;
  }

  public static FileInfo getFile(String groupName, String remoteFileName) {
    try {
      StorageClient storageClient = getTrackerClient();
      return storageClient.get_file_info(groupName, remoteFileName);
    } catch (IOException e) {
      logger.error("IO Exception: Get File from Fast DFS failed", e);
    } catch (Exception e) {
      logger.error("Non IO Exception: Get File from Fast DFS failed", e);
    }
    return null;
  }

  public static InputStream downFile(String groupName, String remoteFileName) {
    try {
      StorageClient storageClient = getTrackerClient();
      byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
      InputStream ins = new ByteArrayInputStream(fileByte);
      return ins;
    } catch (IOException e) {
      logger.error("IO Exception: Get File from Fast DFS failed", e);
    } catch (Exception e) {
      logger.error("Non IO Exception: Get File from Fast DFS failed", e);
    }
    return null;
  }

  public static void deleteFile(String groupName, String remoteFileName)
      throws Exception {
    StorageClient storageClient = getTrackerClient();
    int i = storageClient.delete_file(groupName, remoteFileName);
    logger.info("delete file successfully!!!" + i);
  }

  public static StorageServer[] getStoreStorages(String groupName)
      throws IOException {
    TrackerClient trackerClient = new TrackerClient();
    TrackerServer trackerServer = trackerClient.getConnection();
    return trackerClient.getStoreStorages(trackerServer, groupName);
  }

  public static ServerInfo[] getFetchStorages(String groupName,
                        String remoteFileName) throws IOException {
    TrackerClient trackerClient = new TrackerClient();
    TrackerServer trackerServer = trackerClient.getConnection();
    return trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName);
  }

  public static String getTrackerUrl() throws IOException {
    return "http://"+getTrackerServer().getInetSocketAddress().getHostString()+":"+ClientGlobal.getG_tracker_http_port()+"/";
  }

  private static StorageClient getTrackerClient() throws IOException {
    TrackerServer trackerServer = getTrackerServer();
    StorageClient storageClient = new StorageClient(trackerServer, null);
    return  storageClient;
  }

  private static TrackerServer getTrackerServer() throws IOException {
    TrackerClient trackerClient = new TrackerClient();
    TrackerServer trackerServer = trackerClient.getConnection();
    return  trackerServer;
  }
}
FastDFSFile:
public class FastDFSFile {
private String name;

private byte[] content;

private String ext;

private String md5;

private String author;

public FastDFSFile(String name, byte[] content, String ext, String height,
           String width, String author) {
  super();
  this.name = name;
  this.content = content;
  this.ext = ext;
  this.author = author;
}

public FastDFSFile(String name, byte[] content, String ext) {
  super();
  this.name = name;
  this.content = content;
  this.ext = ext;

}
//set和get方法,自動生成
}      
private static Logger logger = LoggerFactory.getLogger(UploadController.class);
@RequestMapping("/uploadFile1")
    public ModelAndView uploadFile1(@RequestParam("file") MultipartFile file, ModelAndView modelAndView) {
        modelAndView.setViewName("uploadStatus");
        if (file.isEmpty()) {
            modelAndView.addObject("message","上傳失敗,請選擇一個檔案上傳");
            return modelAndView;
        }
        try {
            String path=saveFile(file);
            modelAndView.addObject("path","上傳成功,檔案路徑為:" + path);
            modelAndView.addObject("message","上傳成功,上傳的檔案名為:" + file.getOriginalFilename());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return modelAndView;
    }

public String saveFile(MultipartFile multipartFile) throws IOException {
        String[] fileAbsolutePath={};
        String fileName=multipartFile.getOriginalFilename();
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
        byte[] file_buff = null;
        InputStream inputStream=multipartFile.getInputStream();
        if(inputStream!=null){
            int len1 = inputStream.available();
            file_buff = new byte[len1];
            inputStream.read(file_buff);
        }
        inputStream.close();
        FastDFSFile file = new FastDFSFile(fileName, file_buff, ext);
        try {
            fileAbsolutePath = FastDFSClient.upload(file);  //upload to fastdfs
        } catch (Exception e) {
            logger.error("upload file Exception!",e);
        }
        if (fileAbsolutePath==null) {
            logger.error("upload file failed,please upload again!");
        }
        String path=FastDFSClient.getTrackerUrl()+fileAbsolutePath[0]+ "/"+fileAbsolutePath[1];
        return path;
    }