SpringBoot2.0 整合 FastDFS

前一篇,我們使用docker來部署FastDFS(見 ),這一天我們來試著使用SpringBoot2.0來訪問FastDFS

採用maven配置

1、配置依賴包,修改pom文件

<code>
<dependency>
<groupid>com.github.tobato/<groupid>
<artifactid>fastdfs-client/<artifactid>
<version>1.26.5/<version>
/<dependency>/<code>

2、springboot配置文件添加

<code>fdfs:
# 鏈接超時
connect-timeout: 60
# 讀取時間
so-timeout: 60
# 生成縮略圖參數
thumb-image:
width: 150
height: 150
tracker-list: 192.168.72.130:22122/<code>

3、核心配置類

<code>import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.context.annotation.Import;
import org.springframework.jmx.support.RegistrationPolicy;

import com.github.tobato.fastdfs.FdfsClientConfig;

@Configuration
@Import(FdfsClientConfig.class)
// Jmx重複註冊bean的問題
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class DfsConfig {
}/<code>

4、文件工具類,自己按實際去修改

<code>@Slf4j
public class FileDfsUtil {

@Resource
private FastFileStorageClient storageClient ;
/**
* 上傳文件
*/
public String upload(MultipartFile multipartFile) throws Exception{
String originalFilename = multipartFile.getOriginalFilename().
substring(multipartFile.getOriginalFilename().
lastIndexOf(".") + 1);
StorePath storePath = this.storageClient.uploadImageAndCrtThumbImage(
multipartFile.getInputStream(),
multipartFile.getSize(),originalFilename , null);
return storePath.getFullPath() ;
}
/**
* 刪除文件
*/
public void deleteFile(String fileUrl) {
if (StringUtils.isEmpty(fileUrl)) {
log.info("fileUrl == >>文件路徑為空...");
return;
}
try {
StorePath storePath = StorePath.parseFromUrl(fileUrl);
storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
} catch (Exception e) {
\tlog.info(e.getMessage());
}

}
/<code>

4、請求代碼示例

<code>@RequestMapping("/fastDfs")
\t@ResponseBody
\tpublic Object fastDfs() throws IOException{
\t\tFile fileRoot=new File("F:/images");
\t\t
\t\tFile[] files=fileRoot.listFiles();
for(File file:files){
\tFileInputStream inputFile = new FileInputStream(file);
\t byte[] buffer = new byte[(int)file.length()];
inputFile.read(buffer);
inputFile.close();
\t\treturn fileDfsUtil.uploadFile(Base64Utils.encodeToString(buffer), "jpg");
}
\t\t
return 1;
\t}/<code>

請求上面接口後返回

SpringBoot2.0 整合 FastDFS

訪問 nginx地址

http://127.0.0.1:8888/group1/M00/00/00/rBAGil5Xb5aAON-EAAJV6tHqsvQ252.jpg

可以顯示圖片,即為成功

需要注意的是必須保證springboot所在服務器可以訪問storage的網絡 例如可以訪問storage:23000端口(當然tracker的端口也必須可以訪問)


分享到:


相關文章: