<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>xxx</version>
</dependency>
import com.github.tobato.fastdfs.domain.MateData;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.exception.FdfsException;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Set;
@Component
public class FdfsUtil {
private final Logger logger = LoggerFactory.getLogger(FdfsUtil.class);
@Autowired
private FastFileStorageClient storageClient;
public String uploadFile(MultipartFile file) throws IOException {
StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(),
FilenameUtils.getExtension(file.getOriginalFilename()), null);
return getResAccessUrl(storePath);
}
public String uploadFile(File file) throws IOException {
FileInputStream inputStream = new FileInputStream(file);
StorePath path = storageClient.uploadFile(inputStream, file.length(),
FilenameUtils.getExtension(file.getName()), null);
return getResAccessUrl(path);
}
public String uploadFileStream(InputStream is, long size, String fileName) {
StorePath path = storageClient.uploadFile(is, size, fileName, null);
return getResAccessUrl(path);
}
public String uploadFile(String content, String fileExtension) {
byte[] buff = content.getBytes(StandardCharsets.UTF_8);
ByteArrayInputStream stream = new ByteArrayInputStream(buff);
StorePath path = storageClient.uploadFile(stream, buff.length, fileExtension, null);
return getResAccessUrl(path);
}
private String getResAccessUrl(StorePath storePath) {
return storePath.getFullPath();
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void deleteFile(String fileUrl) throws FdfsException {
if (StringUtils.isEmpty(fileUrl)) {
return;
}
try {
StorePath storePath = StorePath.praseFromUrl(fileUrl);
storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
} catch (FdfsUnsupportStorePathException e) {
logger.warn("删除图片错误:"+e.getMessage());
}
}
public String upfileImage(InputStream is, long size, String fileExtName, Set<MateData> metaData) {
StorePath path = storageClient.uploadImageAndCrtThumbImage(is, size, fileExtName, metaData);
return getResAccessUrl(path);
}
}