pom
<!-- fastdfs -->
<dependency>
<groupId>net.oschina.zcx7878</groupId>
<artifactId>fastdfs-client-java</artifactId>
<version>1.27.0.0</version>
</dependency>
# fastdfs-client.properties
fastdfs.connect_timeout_in_seconds = 5
fastdfs.network_timeout_in_seconds = 30
fastdfs.charset = UTF-8
fastdfs.http_anti_steal_token =
fastdfs.http_secret_key =
fastdfs.http_tracker_http_port = 80
fastdfs.tracker_servers =
#其实storage不用配置
fastdfs.storage_servers =
/**
* 附件上传
*
* @param file
*/
public void uploadFastdfs(MultipartFile file) {
if (file.isEmpty()) {
} else {
String tempFileName = file.getOriginalFilename();
//fastDFS方式
try {
ClientGlobal.initByProperties(getFastDfsProperties());
byte[] fileBuff = file.getBytes();
String fileId = "";
String fileExtName = tempFileName.substring(tempFileName.lastIndexOf(".") + 1);
//建立连接
TrackerClient tracker = new TrackerClient();
TrackerServer trackerServer = tracker.getConnection();
// StorageServer storageServer = tracker.getStoreStorage(trackerServer);
StorageClient1 client = new StorageClient1(trackerServer, null);
//设置元信息
NameValuePair[] metaList = new NameValuePair[3];
metaList[0] = new NameValuePair("fileName", tempFileName);
metaList[1] = new NameValuePair("fileExtName", fileExtName);
metaList[2] = new NameValuePair("fileLength", String.valueOf(file.getSize()));
//上传文件,获得fileId
fileId = client.upload_file1(fileBuff, fileExtName, metaList);
//上传成功后返回存储url地址
// StringBuilder builder = new StringBuilder(storageUrl);
// builder.append(fileId);
// String filePath = "" + builder;
} catch (Exception e) {
log.error("上传附件异常,{}",e);
}
}
}
/**
* 获取FastDfs配置
*/
private String getFastDfsProperties() {
String CLASS_PATH = "";
ApplicationHome home = new ApplicationHome();
File file = home.getSource();
if(file != null && file.exists()){ //外部配置
CLASS_PATH = file.getParentFile().getPath() + File.separator + "config" + File.separator;
return CLASS_PATH + "application-" + propertyType + ".properties";
}else{
return "application-" + propertyType + ".properties";
}
}