fastdfs分布式文件上传
1,首先要导入依赖包,但是fastdfs没有直接的maven依赖,要运行fastdfs的src源文件然后打成war包然后放到maven仓库里面,然后再导入依赖
<dependency>
<groupId>org.csource</groupId>
<artifactId>fastdfs-client-java</artifactId>
<version>1.27-SNAPSHOT</version>
</dependency>
2,由于是文件上传是分布式的,所以自己的本地服务器只是一个向导,真正存储文件的是远程的服务器,,所以需要配置远程服务器的host和port,如:
tracker_server=10.9.251.200:22122
3,文件上传工具类的编写,(上传文件和获取文件的地址)
public FastDfsUtils(String configlocation) throws IOException, MyException {
if (configlocation.startsWith("classpath")) {
configlocation = configlocation.replace("classpath:", getClass().getResource("/").getPath());
}
ClientGlobal.init(configlocation);
trackerClient = new TrackerClient();
trackerServer = trackerClient.getConnection();
}
public String fileUpload(byte[] bs, String ext_name) throws IOException, MyException {
return fileUpload(bs, ext_name, null);
}
public String fileUpload(byte[] bs, String ext_name, NameValuePair[] valuePair) throws IOException, MyException {
StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer);
String[] resultString = storageClient1.upload_file(bs, ext_name, valuePair);
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < resultString.length; i++) {
stringBuffer.append(resultString[i]);
if (i == 0) {
stringBuffer.append("/");
}
}
return stringBuffer.toString();
}
4,工具类编写完成,得手动创建对象,然后注入Controller实现层里面
@Bean
public FastDfsUtils fastDfsUtils() throws IOException, MyException {
FastDfsUtils fastDfsUtils=new FastDfsUtils("classpath:conf.properties");
return fastDfsUtils;
}
5,Controller实现层的具体应用
@AutoWried
private FastDfsUtils fastDfsUtils;
String originalFilename = file1.getOriginalFilename();
String ext_name = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
String file1address = fastDfsUtils.fileUpload(file1.getBytes(), ext_name);