在SpringBoot中使用FastDFS,这里并没使用原始作者余庆开发的java客户端,采用的是github上一个位开发者自己封装支持springboot的java客户端。
GitHub地址:https://github.com/tobato/FastDFS_Client
FastDFS安装:https://blog.csdn.net/u013089490/article/details/83992738
1、pom文件
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.26.4</version>
</dependency>
2、FastDFS配置类
import com.github.tobato.fastdfs.FdfsClientConfig;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.context.annotation.Import;
import org.springframework.jmx.support.RegistrationPolicy;
/**
* FastDFS-Client客户端配置类
*/
@Configuration
@Import(FdfsClientConfig.class)
// 解决jmx重复注册bean的问题
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class FastClientImporter {
}
3、测试代码
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.domain.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;
/**
* @ClassName UploadTest
**/
@RunWith(SpringRunner.class)
@SpringBootTest
public class UploadTest {
@Autowired
private FastFileStorageClient storageClient;
//注入缩略图
@Autowired
private ThumbImageConfig thumbImageConfig;
@Test
public void testUpload() throws FileNotFoundException {
File file = new File("D:\\0.jpg");
// 上传并且生成缩略图
StorePath storePath = this.storageClient.uploadFile(
new FileInputStream(file), file.length(), "jpg", null);
// 带分组的路径,返回值是group1/M00/00/00/wKgCDlvtAU-AINxgAABhiHhXJUs106.jpg
System.out.println(storePath.getFullPath());//getFullPath()返回的是全路径
// 不带分组的路径,返回值是M00/00/00/wKgCDlvtAU-AINxgAABhiHhXJUs106.jpg
System.out.println(storePath.getPath());
}
@Test
public void testUploadAndCreateThumb() throws FileNotFoundException {
File file = new File("D:\\0.jpg");
// 上传并且生成缩略图
StorePath storePath = this.storageClient.uploadImageAndCrtThumbImage(
new FileInputStream(file), file.length(), "jpg", null);
// 带分组的路径
System.out.println(storePath.getFullPath());
// 不带分组的路径
System.out.println(storePath.getPath());
// 获取缩略图路径
String path = thumbImageConfig.getThumbImagePath(storePath.getPath());
System.out.println(path);
}
}