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), file.length(), "png", null);
// 帶分組的路徑
System.out.println(storePath.getFullPath());
// 不帶分組的路徑
System.out.println(storePath.getPath());
// 獲取縮略圖路徑
String path = thumbImageConfig.getThumbImagePath(storePath.getPath());
System.out.println(path);
}
}