springboot整合fastdfs详细结构及代码
时间: 2023-09-17 20:12:11 浏览: 117
springboot整合代码
好的,关于springboot整合fastdfs的详细结构和代码,我可以给出以下步骤和示例代码:
1. 在pom.xml中添加fastdfs-client-java的依赖,如下所示:
```xml
<dependency>
<groupId>org.csource</groupId>
<artifactId>fastdfs-client-java</artifactId>
<version>1.29</version>
</dependency>
```
2. 创建配置类FastDFSConfig,进行FastDFS的配置,如下所示:
```java
@Configuration
public class FastDFSConfig {
@Value("${fastdfs.tracker_servers}")
private String tracker_servers;//tracker服务地址
@Value("${fastdfs.connect_timeout_in_seconds}")
private int connect_timeout_in_seconds;//连接超时时间
@Value("${fastdfs.network_timeout_in_seconds}")
private int network_timeout_in_seconds;//网络超时时间
@Value("${fastdfs.charset}")
private String charset;//字符集
/**
* fastDFS文件上传客户端
*
* @return
* @throws Exception
*/
@Bean
public TrackerClient trackerClient() throws Exception {
TrackerClient trackerClient = new TrackerClient();
trackerClient.setGCharset(charset);
trackerClient.setTrackerServer(new InetSocketAddress(tracker_servers.split(":")[0], Integer.parseInt(tracker_servers.split(":")[1])));
trackerClient.setNetworkTimeout(network_timeout_in_seconds * 1000);
trackerClient.setConnectTimeout(connect_timeout_in_seconds);
return trackerClient;
}
}
```
3. 创建工具类FastDFSUtil,封装文件上传、删除等操作,如下所示:
```java
@Component
public class FastDFSUtil {
@Autowired
private TrackerClient trackerClient;
/**
* 上传文件
*
* @param file
* @return
*/
public String upload(MultipartFile file) throws Exception {
byte[] bytes = file.getBytes();
String originalFilename = file.getOriginalFilename();
String extName = StringUtils.getFilenameExtension(originalFilename);
StorageClient1 storageClient1 = new StorageClient1(trackerClient.getConnection(), null);
String fileId = storageClient1.upload_file1(bytes, extName, null);
return fileId;
}
/**
* 根据文件id删除文件
*
* @param fileId
*/
public void delete(String fileId) throws Exception {
StorageClient1 storageClient1 = new StorageClient1(trackerClient.getConnection(), null);
int i = storageClient1.delete_file1(fileId);
if (i != 0) {
throw new Exception("删除文件失败!");
}
}
}
```
通过以上的代码就可以实现在springboot中整合fastdfs了。需要注意的是,在进行文件的上传、删除等操作时需要在配置文件中配置tracker服务地址、连接超时时间、网络超时时间、字符集等参数。
阅读全文