springboot项目中使用fastdfs文件数据库开发应用

编程

安装并启动fastdfs,方法如:https://gitee.com/lion123/springboot-fdfs-demo

创建springboot项目,并导入fastdfs jar 包

<dependency>

<groupId>com.github.tobato</groupId>

<artifactId>fastdfs-client</artifactId>

<version>1.26.6</version>

</dependency>

添加fastdfs配置类

@Import(FdfsClientConfig.class)

@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)

public class FdfsConfig {

}

添加fastdfs工具类

@Slf4j

@Component

public class FastDFSClient {

@Autowired

private FastFileStorageClient storageClient;

@Autowired

private FdfsWebServer fdfsWebServer;

/**

* 上传文件

*

* @param file 文件对象

* @return 文件访问地址

* @throws IOException

*/

public String uploadFile(MultipartFile file) throws IOException {

StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(),

FilenameUtils.getExtension(file.getOriginalFilename()), null);

return getResAccessUrl(storePath);

}

/**

* 上传文件

*

* @param file 文件对象

* @return 文件访问地址

* @throws IOException

*/

public String uploadFile(File file) throws IOException {

FileInputStream inputStream = new FileInputStream(file);

StorePath storePath = storageClient.uploadFile(inputStream, file.length(),

FilenameUtils.getExtension(file.getName()), null);

return getResAccessUrl(storePath);

}

/**

* 将一段字符串生成一个文件上传

*

* @param content 文件内容

* @param fileExtension

* @return

*/

public String uploadFile(String content, String fileExtension) {

byte[] buff = content.getBytes(Charset.forName("UTF-8"));

ByteArrayInputStream stream = new ByteArrayInputStream(buff);

StorePath storePath = storageClient.uploadFile(stream, buff.length, fileExtension, null);

return getResAccessUrl(storePath);

}

// 封装图片完整URL地址

private String getResAccessUrl(StorePath storePath) {

String fileUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();

return fileUrl;

}

/**

* 下载文件

*

* @param fileUrl 文件url

* @return

*/

public byte[] download(String fileUrl) {

String group = fileUrl.substring(0, fileUrl.indexOf("/"));

String path = fileUrl.substring(fileUrl.indexOf("/") + 1);

byte[] bytes = storageClient.downloadFile(group, path, new DownloadByteArray());

return bytes;

}

/**

* 删除文件

*

* @param fileUrl 文件访问地址

* @return

*/

public void deleteFile(String fileUrl) {

if (StringUtils.isEmpty(fileUrl)) {

return;

}

try {

StorePath storePath = StorePath.parseFromUrl(fileUrl);

storageClient.deleteFile(storePath.getGroup(), storePath.getPath());

} catch (FdfsUnsupportStorePathException e) {

log.warn(e.getMessage());

}

}

}

源码示例:https://gitee.com/lion123/springboot-fdfs-demo

 

以上是 springboot项目中使用fastdfs文件数据库开发应用 的全部内容, 来源链接: utcz.com/z/514591.html

回到顶部