1. 引入依賴
在父工程中,咱們已經管理了依賴,版本爲:java
<fastDFS.client.version>1.26.7</fastDFS.client.version>
所以,這裏咱們直接在工程的pom.xml中引入座標便可:git
<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), file.length(), "png", null); // 帶分組的路徑 System.out.println(storePath.getFullPath()); // 不帶分組的路徑 System.out.println(storePath.getPath()); // 獲取縮略圖路徑 String path = thumbImageConfig.getThumbImagePath(storePath.getPath()); System.out.println(path); } }