1. 程式人生 > >FastDFS通過java上傳檔案到伺服器

FastDFS通過java上傳檔案到伺服器

GitHub原文地址點選進入

一、FastDFS簡介及系統環境搭建:點選進入

二、FastDFS 配置 Nginx 模組及訪問測試:點選進入

三、FastDFS使用流程介紹:

我們在專案中使用fastdfs+nginx+mysql實現上傳附件的功能,主要原理就是將附件上傳到fastdfs得到一個檔案的連結路徑url,我們獲取到這個url將他以字串形式儲存到我們的mysql中,下載的時候獲取到這個url直接開啟或者下載附件
這裡寫圖片描述這裡寫圖片描述

四、實現程式碼:

1,配置依賴:因為我們使用的maven來管理工程,所以我們需要去新增pom檔案依賴

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

注意:由於fastdfs-client-java jar包沒有上傳到中央倉庫,所以需要下載原始碼進行maven編譯再上傳到私服,然後通過私服下載,具體流程參照步驟一,或者通過jar包的形式進行下載:
下載地址:點選進入

2,配置資訊:我這裡是配置在 application.properties 檔案中的

#FastDFS配置begin-----------除了fastdfs.tracker_servers,其它配置項都是可選的
fastdfs.connect
_timeout_in_seconds=5 fastdfs.network_timeout_in_seconds=30 fastdfs.charset=UTF-8 fastdfs.http_anti_steal_token=false fastdfs.http_secret_key=FastDFS1234567890 fastdfs.http_tracker_http_port=8070 fastdfs.tracker_servers=192.168.2.200:22122 #FastDFS配置end-----------

這裡寫圖片描述
3,具體實現程式碼:

/**
  * 上傳檔案到FastDFS
  *
  * @param file
  */
 @RequestMapping(value = "/fastDFSUpload", method = RequestMethod.POST)
 @ResponseBody
 public void fastDFSUpload(MultipartFile file) {

     String ext_Name = file.getOriginalFilename().split("\\.")[1];
     String file_Name = file.getOriginalFilename().split("\\.")[0];

     byte[] bytes = null;
     try {
         bytes = file.getBytes();
     } catch (IOException e) {
         e.printStackTrace();
     }

     String videoPath = uploadFile(bytes, ext_Name, file_Name);
 }

 /**
  * FastDFS實現檔案下載
  *
  * @param filePath
  */
 @RequestMapping(value = "/fastDFSDownload", method = RequestMethod.GET)
 @ResponseBody
 public void fastDFSDownload(String filePath) {
     try {
         ClientGlobal.initByProperties("application.properties");

         // 連結FastDFS伺服器,建立tracker和Stroage
         TrackerClient trackerClient = new TrackerClient();
         TrackerServer trackerServer = trackerClient.getConnection();

         String storageServerIp = getStorageServerIp(trackerClient, trackerServer);
         StorageServer storageServer = getStorageServer(storageServerIp);
         StorageClient storageClient = new StorageClient(trackerServer, storageServer);
         byte[] b = storageClient.download_file("group1", filePath);
         if (b == null) {
             throw new IOException("檔案" + filePath + "不存在");
         }

         String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
         FileOutputStream fileOutputStream = new FileOutputStream("c://" + fileName);
         IOUtils.write(b, fileOutputStream);
         fileOutputStream.close();
     } catch (Exception e) {
         e.printStackTrace();
     }
 }

 /**
  * FastDFS獲取將上傳檔案資訊
  */
 @RequestMapping(value = "/fastDFSGetFileInfo", method = RequestMethod.GET)
 @ResponseBody
 public void fastDFSGetFileInfo(String filePath) {
     try {
         // 連結FastDFS伺服器,建立tracker和Stroage
         ClientGlobal.initByProperties("application.properties");
         TrackerClient trackerClient = new TrackerClient();
         TrackerServer trackerServer = trackerClient.getConnection();

         String storageServerIp = getStorageServerIp(trackerClient, trackerServer);
         StorageServer storageServer = getStorageServer(storageServerIp);
         StorageClient storageClient = new StorageClient(trackerServer, storageServer);

         FileInfo fi = storageClient.get_file_info("group1", filePath);
         if (fi == null) {
             throw new IOException("檔案" + filePath + "不存在");
         }

         log.debug("檔案資訊=" + fi.toString());
     } catch (Exception e) {
         e.printStackTrace();
     }
 }

 /**
  * FastDFS獲取檔名稱
  */
 @RequestMapping(value = "/fastDFSGetFileName", method = RequestMethod.GET)
 @ResponseBody
 public void fastDFSGetFileName(String filePath) {
     try {
         // 連結FastDFS伺服器,建立tracker和Stroage
         ClientGlobal.initByProperties("application.properties");
         TrackerClient trackerClient = new TrackerClient();
         TrackerServer trackerServer = trackerClient.getConnection();

         String storageServerIp = getStorageServerIp(trackerClient, trackerServer);
         StorageServer storageServer = getStorageServer(storageServerIp);
         StorageClient storageClient = new StorageClient(trackerServer, storageServer);

         NameValuePair[] nvps = storageClient.get_metadata("group1", filePath);
         if (nvps == null) {
             throw new IOException("檔案" + filePath + "不存在");
         }

         log.debug(nvps[0].getName() + "." + nvps[0].getValue());
     } catch (Exception e) {
         e.printStackTrace();
     }
 }

 /**
  * FastDFS實現刪除檔案
  */
 @RequestMapping(value = "/fastDFSDelete", method = RequestMethod.GET)
 @ResponseBody
 public void fastDFSDelete(String filePath) {
     try {
         // 連結FastDFS伺服器,建立tracker和Stroage
         ClientGlobal.initByProperties("application.properties");
         TrackerClient trackerClient = new TrackerClient();
         TrackerServer trackerServer = trackerClient.getConnection();

         String storageServerIp = getStorageServerIp(trackerClient, trackerServer);
         StorageServer storageServer = getStorageServer(storageServerIp);
         StorageClient storageClient = new StorageClient(trackerServer, storageServer);

         int i = storageClient.delete_file("group1", filePath);
         log.debug(i == 0 ? "刪除成功" : "刪除失敗:" + i);
     } catch (Exception e) {
         e.printStackTrace();
     }
 }

 public String uploadFile(byte[] byteFile, String ext_file, String file_Name) {

     // 拼接服務區的檔案路徑
     StringBuffer sbPath = new StringBuffer();
     sbPath.append("http://192.168.2.200/uploads/");
     try {
         // 初始化檔案資源
         ClientGlobal.initByProperties("application.properties");

         // 連結FastDFS伺服器,建立tracker和Stroage
         TrackerClient trackerClient = new TrackerClient();
         TrackerServer trackerServer = trackerClient.getConnection();

         String storageServerIp = getStorageServerIp(trackerClient, trackerServer);
         StorageServer storageServer = getStorageServer(storageServerIp);
         StorageClient storageClient = new StorageClient(trackerServer, storageServer);

         //利用位元組流上傳檔案
//            NameValuePair[] nvps = new NameValuePair[1];
//            nvps[0] = new NameValuePair(file_Name, ext_file);
         String[] strings = storageClient.upload_file(byteFile, ext_file, null);

         sbPath.append(StrUtil.join("/", strings));
         log.debug("上傳路徑=" + sbPath.toString());
     } catch (IOException | MyException e) {
         e.printStackTrace();
     }
     return sbPath.toString();
 }

 /**
  * 得到Storage服務
  *
  * @param storageIp
  * @return 返回Storage服務
  */
 private static StorageServer getStorageServer(String storageIp) {
     StorageServer storageServer = null;
     if (storageIp != null && !("").equals(storageIp)) {
         try {
             // ip port store_path下標
             storageServer = new StorageServer(storageIp, 23000, 1);
         } catch (IOException e) {
             e.printStackTrace();
         }
     }
     log.debug("——storage server生成");
     return storageServer;
 }

 /**
  * 獲得可用的storage IP
  *
  * @param trackerClient
  * @param trackerServer
  * @return 返回storage IP
  */
 private static String getStorageServerIp(TrackerClient trackerClient, TrackerServer trackerServer) {
     String storageIp = null;
     if (trackerClient != null && trackerServer != null) {
         try {
             StorageServer storageServer = trackerClient.getStoreStorage(trackerServer, "group1");
             storageIp = storageServer.getSocket().getInetAddress().getHostAddress();
         } catch (IOException e) {
             e.printStackTrace();
         }
     }
     log.debug("——獲取組中可用的storage IP——" + storageIp);
     return storageIp;
 }

五、效果檢視

這裡寫圖片描述
直接就可以整合swagger通過api介面上傳檔案了,搭建好nginx環境後可以通過返回的url路徑訪問上傳的檔案,別的就不再一一演示了,自己去檢視效果吧