增加依赖
com.github.tobato fastdfs-client 1.25.2-RELEASE
配置文件增加
fdfs: soTimeout: 10000 connectTimeout: 10000 thumbImage: #缩略图生成参数 width: 100 height: 100 trackerList: #TrackerList参数,支持多个 - 192.168.1.100:22122
启动类增加
@Import(FdfsClientConfig.class)//解决jmx重复注册bean的问题@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
FastdfsClientUtils
package com.zns.utils;import com.github.tobato.fastdfs.domain.StorePath;import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;import com.github.tobato.fastdfs.service.FastFileStorageClient;import org.apache.commons.io.FilenameUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import org.springframework.web.multipart.MultipartFile;import java.io.*;import java.nio.charset.Charset;@Componentpublic class FastdfsClientUtils { @Autowired private FastFileStorageClient storageClient; /** * 上传文件 * * @param file * @return * @throws IOException */ public String uploadFile(MultipartFile file) throws Exception { StorePath storePath = storageClient.uploadFile((InputStream) file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null); return storePath.getFullPath(); } /** * 上传文件 * * @param file * @return * @throws IOException */ public String uploadFile(File file) throws Exception { FileInputStream inputStream = new FileInputStream(file); StorePath storePath = storageClient.uploadFile(inputStream, file.length(), FilenameUtils.getExtension(file.getName()), null); return storePath.getFullPath(); } /** * 将一段字符串生成一个文件上传 * * @param content 文件内容 * @param fileExtension * @return */ public String uploadFile(String content, String fileExtension) throws Exception { byte[] buff = content.getBytes(Charset.forName("UTF-8")); ByteArrayInputStream stream = new ByteArrayInputStream(buff); StorePath storePath = storageClient.uploadFile(stream, buff.length, fileExtension, null); return storePath.getFullPath(); } /** * 删除文件 * * @param fileUrl 文件访问地址 * @return */ public void deleteFile(String fileUrl) throws Exception { StorePath storePath = StorePath.praseFromUrl(fileUrl); storageClient.deleteFile(storePath.getGroup(), storePath.getPath()); } /** * 下载文件 * * @param fileUrl * @return * @throws Exception */ public byte[] download(String fileUrl) throws Exception { StorePath storePath = StorePath.praseFromUrl(fileUrl); byte[] bytes = storageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadByteArray()); return bytes; }}