실전 FastDFS Java 클 라 이언 트 업로드 파일
10706 단어 자바
분산 파일 시스템 의 FastDFS
FastDFS Java 클 라 이언 트 설치
먼저 GitHub 에서 프로젝트 원본 을 복제 합 니 다.
$ git clone https://github.com/happyfish100/fastdfs-client-java.git
그리고 Nexus 의존 사복 에 배치 하 는 것 을 잊 지 마 세 요:
$ mvn clean install deploy
마지막 으로 필요 한 항목 에 POM 의존 도 를 추가 하면 됩 니 다.
org.csource
fastdfs-client-java
1.27-SNAPSHOT
의존 도 를 도입 한 후
application.yml
에 FastDFS 서버 설정 을 추가 합 니 다.fastdfs:
base:
# Nginx
url: http://{fastdfs_server ip}/
storage:
type: fastdfs
fastdfs:
tracker_server: {tracker_server ip}
FastDFS 도구 클래스 만 들 기
정의 파일 저장 인터페이스
package com.antoniopeng.fastdfs.service.upload;
/**
*
*/
public interface StorageService {
/**
*
*
* @param data
* @param extName
* @return id; null
*/
public String upload(byte[] data, String extName);
/**
*
*
* @param fileId id
* @return 0,
*/
public int delete(String fileId);
}
파일 저장 인터페이스 구현
package com.antoniopeng.fastdfs.service.upload;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerGroup;
import org.csource.fastdfs.TrackerServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
/**
*
*/
public class FastDFSStorageService implements StorageService, InitializingBean {
private static final Logger logger = LoggerFactory.getLogger(FastDFSStorageService.class);
private TrackerClient trackerClient;
@Value("${storage.fastdfs.tracker_server}")
private String trackerServer;
@Override
public String upload(byte[] data, String extName) {
TrackerServer trackerServer = null;
StorageServer storageServer = null;
StorageClient1 storageClient1 = null;
try {
NameValuePair[] meta_list = null; // new NameValuePair[0];
trackerServer = trackerClient.getConnection();
if (trackerServer == null) {
logger.error("getConnection return null");
}
storageServer = trackerClient.getStoreStorage(trackerServer);
storageClient1 = new StorageClient1(trackerServer, storageServer);
String fileid = storageClient1.upload_file1(data, extName, meta_list);
logger.debug("uploaded file ", fileid);
return fileid;
} catch (Exception ex) {
logger.error("Upload fail", ex);
return null;
} finally {
if (storageServer != null) {
try {
storageServer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (trackerServer != null) {
try {
trackerServer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
storageClient1 = null;
}
}
@Override
public int delete(String fileId) {
TrackerServer trackerServer = null;
StorageServer storageServer = null;
StorageClient1 storageClient1 = null;
int index = fileId.indexOf('/');
String groupName = fileId.substring(0, index);
try {
trackerServer = trackerClient.getConnection();
if (trackerServer == null) {
logger.error("getConnection return null");
}
storageServer = trackerClient.getStoreStorage(trackerServer, groupName);
storageClient1 = new StorageClient1(trackerServer, storageServer);
int result = storageClient1.delete_file1(fileId);
return result;
} catch (Exception ex) {
logger.error("Delete fail", ex);
return 1;
} finally {
if (storageServer != null) {
try {
storageServer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (trackerServer != null) {
try {
trackerServer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
storageClient1 = null;
}
}
@Override
public void afterPropertiesSet() throws Exception {
File confFile = File.createTempFile("fastdfs", ".conf");
PrintWriter confWriter = new PrintWriter(new FileWriter(confFile));
confWriter.println("tracker_server=" + trackerServer);
confWriter.close();
ClientGlobal.init(confFile.getAbsolutePath());
confFile.delete();
TrackerGroup trackerGroup = ClientGlobal.g_tracker_group;
trackerClient = new TrackerClient(trackerGroup);
logger.info("Init FastDFS with tracker_server : {}", trackerServer);
}
}
파일 저장 소 클래스 만 들 기
package com.antoniopeng.fastdfs.service.upload;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import java.util.HashMap;
import java.util.Map;
/**
*
*/
public class StorageFactory implements FactoryBean {
@Autowired
private AutowireCapableBeanFactory acbf;
/**
* , fastdfs
*/
@Value("${storage.type}")
private String type;
private Map> classMap;
public StorageFactory() {
classMap = new HashMap<>();
classMap.put("fastdfs", FastDFSStorageService.class);
}
@Override
public StorageService getObject() throws Exception {
Class extends StorageService> clazz = classMap.get(type);
if (clazz == null) {
throw new RuntimeException("Unsupported storage type [" + type + "], valid are " + classMap.keySet());
}
StorageService bean = clazz.newInstance();
acbf.autowireBean(bean);
acbf.initializeBean(bean, bean.getClass().getSimpleName());
return bean;
}
@Override
public Class> getObjectType() {
return StorageService.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
프로필 저장 소 클래스
package com.antoniopeng.fastdfs.service.upload;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Java StorageFactory Bean
*/
@Configuration
public class FastDFSConfiguration {
@Bean
public StorageFactory storageFactory() {
return new StorageFactory();
}
}
FastDFS 접근 컨트롤 러 만 들 기
package com.antoniopeng.fastdfs.controller.upload;
import com.antoniopeng.fastdfs.service.upload.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
public class UploadController {
@Value("${fastdfs.base.url}")
private String FASTDFS_BASE_URL;
@Autowired
private StorageService storageService;
/**
*
*
* @param dropFile Dropzone
* @param editorFiles wangEditor
* @return
*/
@RequestMapping(value = "upload", method = RequestMethod.POST)
public Map upload(MultipartFile dropFile, MultipartFile[] editorFiles) {
Map result = new HashMap<>();
// Dropzone
if (dropFile != null) {
result.put("fileName", writeFile(dropFile));
}
// wangEditor
if (editorFiles != null && editorFiles.length > 0) {
List fileNames = new ArrayList<>();
for (MultipartFile editorFile : editorFiles) {
fileNames.add(writeFile(editorFile));
}
result.put("errno", 0);
result.put("data", fileNames);
}
return result;
}
/**
*
*
* @param multipartFile
* @return
*/
private String writeFile(MultipartFile multipartFile) {
//
String oName = multipartFile.getOriginalFilename();
String extName = oName.substring(oName.lastIndexOf(".") + 1);
//
String url = null;
try {
String uploadUrl = storageService.upload(multipartFile.getBytes(), extName);
url = FASTDFS_BASE_URL + uploadUrl;
} catch (IOException e) {
e.printStackTrace();
}
//
return url;
}
}
글 쓴 이:팽 초
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.