通过java项目上传文件到SeaweedFs
官方提供了java操作文件的工具类。maven项目使用如下配置
<dependency>
<groupId>com.github.chrislusf</groupId>
<artifactId>seaweedfs-client</artifactId>
<version>3.33</version>
</dependency>
创建一个上传文件的工具类SeaweedTemplate
package com.clwl.bigdata.applications.config;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import seaweedfs.client.FilerClient;
import seaweedfs.client.SeaweedOutputStream;
import java.util.Date;
@Component
public class SeaweedTemplate {
@Value("${seaweedfs.master.host}")
private String weed_location;
@Value("${seaweedfs.master.port}")
private Integer weed_filer_port;
/**
* 上传文件到filer
* @param prefix 存储路径
* @param file 上传文件对象
* @return
* @throws Exception
*/
public String uploadFile(String prefix, MultipartFile file) throws Exception {
FilerClient filerClient = new FilerClient(weed_location, weed_filer_port);
String fileName = "/" + prefix + "/" + DateFormatUtils.format(new Date(), "yyyyMMdd") + "/" +DateFormatUtils.format(new Date(),"HHmmssSSS") +"_"+file.getOriginalFilename();
SeaweedOutputStream seaweedOutputStream = new SeaweedOutputStream(filerClient, fileName);
byte[] fileByte = file.getBytes();
seaweedOutputStream.write(fileByte);
seaweedOutputStream.flush();
seaweedOutputStream.close();
return fileName;
}
/**
* 删除文件
* @param filePath 文件路径
*/
public boolean deleteFile(String filePath){
FilerClient filerClient = new FilerClient(weed_location, weed_filer_port);
return filerClient.rm(filePath,true,true);
}
}
文件上传完成之后直接使用上传文件方法返回的路径,前面拼接上filer的服务的ip和端口号即可直接查看访问。