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 {
//classpath:conf.properties ===>從項目路徑找這個conf的檔案,然後轉換成絕對路徑
if (configlocation.startsWith("classpath")) {
//從項目路徑中查找檔案
configlocation = configlocation.replace("classpath:", getClass().getResource("/").getPath());
// ClassLoader classLoader = FastDfsUtils.class.getClassLoader();//擷取類加載器
// String path = classLoader.getResource("/").getPath();//擷取項目所在的目錄位置
}
//"classpath:xxx.conf"
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);