java操作seaweedfs
前置条件是seaweedfs服务已成功启动,具体部署可参考我上篇文章SeaweedFS部署及使用指南
- 首先导入pom依赖
<dependency>
<groupId>net.anumbrella.seaweedfs</groupId>
<artifactId>seaweedfs-java-client</artifactId>
<version>0.0.2.RELEASE</version>
</dependency>
- 编写SeaweedFS配置类SeaweedFSConfig
@Configuration
public class SeaweedFSConfig {
@Value("${seaweedfs.host}")
private String host;
@Value("${seaweedfs.port}")
private int port;
@Bean
public FileTemplate fileTemplate() {
FileSource fileSource = new FileSource();
// SeaweedFS master服务ip地址
fileSource.setHost(host);
// SeaweedFS master服务端口
fileSource.setPort(port);
try {
// 启动服务
fileSource.startup();
} catch (IOException e) {
e.printStackTrace();
}
return new FileTemplate(fileSource.getConnection());
}
}
我的application.properties配置文件如下:
seaweedfs.host=192.168.1.55 #多个ip地址用逗号隔开
seaweedfs.port=9333
- 上传文件的方法如下,用的是Spring的JUnit测试:
@Autowired
private FileTemplate template;
@Test
public void testSeaweedFS() throws IOException {
// 上传可以指定文件名
FileHandleStatus handleStatus = template.saveFileByStream("new_name.pdf", new FileInputStream(new File("C:\\Users\\xuyan\\Desktop\\test.pdf")));
// 获取文件ID,可通过这个ID获取到文件
String fileId = handleStatus.getFileId();
StreamResponse fileStream = template.getFileStream(fileId);
InputStream inputStream = fileStream.getInputStream();
// 获取流之后流拷贝输出到本地
IOUtils.copy(inputStream,new FileOutputStream(new File("D:/new_name.pdf")));
}
SeaweedFS 上传附件接口方法2
@Autowired
private FileTemplate template;
/**
* @Description: 上传附件接口
* @Date: 2019/12/19
*/
@PostMapping("/upload")
@ApiOperation(value = "上传附件接口", notes = "上传附件,上传成功返回附件id")
public RestResponse<FileHandleStatus> uploadFile(@RequestParam(name = "fileId",required = false) String fileId, @RequestParam("excelFile") MultipartFile file) throws IOException {
try {
if (file.isEmpty()) {
return RestResponse.fail().setMsg("上传文件不能为空!");
}
if (!StringUtils.isEmpty(fileId)){
return RestResponse.ok(template.updateFileByStream(fileId,file.getOriginalFilename(),file.getInputStream()));
}
ContentType contentType = ContentType.create("application/x-www-form-urlencoded", Consts.ISO_8859_1);
return RestResponse.ok(template.saveFileByStream(file.getOriginalFilename(), file.getInputStream(),contentType));
} catch (Exception e) {
logger.error("上传附件失败", e);
return RestResponse.fail().setMsg("上传附件服务连接关闭");
}
}
SeaweedFS 下载附件接口方法2
@Autowired
private FileTemplate template;
/**
* @Description: 上传附件接口
* @Date: 2019/12/19
*/
@GetMapping("/getFileInfo/{fileId}")
@ApiOperation(value="公共下载附件接口",notes = "公共下载附件接口")
@ApiImplicitParams(value = {@ApiImplicitParam(name = "fileId", value = "附件id", dataType = "String", required = true)})
public RestResponse<SeaweedResponse> getFileInfo(@PathVariable String fileId) throws IOException {
FileHandleStatus status = template.getFileStatus(fileId);
String name = new String(status.getFileName().substring(8,status.getFileName().length()-1).getBytes("iso-8859-1"),"utf-8");
SeaweedResponse response = new SeaweedResponse();
if (status != null){
response.setFileId(status.getFileId());
response.setFileName(name);
response.setFilePath(template.getFileUrl(fileId));
}
return RestResponse.ok(response);
}
ps:
解决升级seaweed服务器,导致的获取附件名称时get (“Content-Disposition”) 报 NullPointerException 的问题(完善)
/**
* 获取附件的详情
* @return
*/
@GetMapping("/getFileInfo/{fileId}")
@ApiOperation(value="公共下载附件接口",notes = "下载附件接口")
@ApiImplicitParams(value = {@ApiImplicitParam(name = "fileId", value = "附件id", dataType = "String", required = true)})
public RestResponse<SeaweedResponse> getFileInfo(@PathVariable String fileId) throws IOException {
CloseableHttpClient client = null;
String name = "未命名";
try {
String url = getTemplate().getFileUrl(fileId);
client = HttpClientBuilder.create().build();
HttpGet get = new HttpGet(url);
get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
HttpResponse response = client.execute(get);
String s = response.getFirstHeader("Content-Disposition").getValue();
name = new String(s.substring(18,s.length()-1).getBytes("iso-8859-1"), "utf-8");
}
catch (Exception e){
reConnect();
logger.error("公共下载附件出错",e);
}
finally {
if(client != null)
{
client.close();
}
}
SeaweedResponse response = new SeaweedResponse();
response.setFileId(fileId);
response.setFileName(name);
response.setFilePath(getTemplate().getFileUrl(fileId));
return RestResponse.ok(response);
}
三、SeaweedFS 删除附件接口
@Autowired
private FileTemplate template;
/**
* @Description: 上传附件接口
* @Date: 2019/12/19
*/
@PostMapping("/delete")
@ApiOperation(value="公共删除附件接口",notes = "删除附件接口")
public RestResponse deleteFile(@RequestParam(name = "fileId") String fileId) throws IOException {
if (StringUtils.isEmpty(fileId)) {
return RestResponse.fail().setMsg("fileId 参数不能为空");
}
template.deleteFile(fileId);
return RestResponse.ok("删除成功");
}