1. 程式人生 > 程式設計 >springboot2.0如何通過fastdfs實現檔案分散式上傳

springboot2.0如何通過fastdfs實現檔案分散式上傳

這篇文章主要介紹了springboot2.0如何通過fastdfs實現檔案分散式上傳,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

1. 引入依賴

在父工程中,我們已經管理了依賴,版本為:

<fastDFS.client.version>1.26.7</fastDFS.client.version>

因此,這裡我們直接在工程的pom.xml中引入座標即可:

<dependency>
  <groupId>com.github.tobato</groupId>
  <artifactId>fastdfs-client</artifactId>
</dependency>

@Configuration
@Import(FdfsClientConfig.class)
// 解決jmx重複註冊bean的問題
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class FastClientImporter {
}

2. 在application.yml檔案中編寫FastDFS屬性

fdfs:
 so-timeout: 1501 # 超時時間
 connect-timeout: 601 # 連線超時時間
 thumb-image: # 縮圖
  width: 60
  height: 60
 tracker-list: # tracker地址:你的虛擬機器伺服器地址+埠(預設是22122)
  - 192.168.0.22:22122

3. 測試

package com.leyou.upload.test;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.fdfs.ThumbImageConfig;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

/**
 * @author john
 * @date 2019/12/6 - 15:09
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class FastDFSTest {

  @Autowired
  private FastFileStorageClient storageClient;

  @Autowired
  private ThumbImageConfig thumbImageConfig;

  @Test
  public void testUpload() throws FileNotFoundException {
    // 要上傳的檔案
    File file = new File("D:\\imooc\\project\\images\\1.jpg");
    // 上傳並儲存圖片,引數:1-上傳的檔案流 2-檔案的大小 3-檔案的字尾 4-可以不管他
    StorePath storePath = this.storageClient.uploadFile(
        new FileInputStream(file),file.length(),"jpg",null);
    // 帶分組的路徑
    System.out.println(storePath.getFullPath());
    // 不帶分組的路徑
    System.out.println(storePath.getPath());
  }
  @Test
  public void testUploadAndCreateThumb() throws FileNotFoundException {
    File file = new File("D:\\imooc\\project\\images\\2.jpg");
    // 上傳並且生成縮圖
    StorePath storePath = this.storageClient.uploadImageAndCrtThumbImage(
        new FileInputStream(file),"png",null);
    // 帶分組的路徑
    System.out.println(storePath.getFullPath());
    // 不帶分組的路徑
    System.out.println(storePath.getPath());
    // 獲取縮圖路徑
    String path = thumbImageConfig.getThumbImagePath(storePath.getPath());
    System.out.println(path);
  }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。