package com.farriver.bwf.service.common; import com.farriver.bwf.common.model.ApiData; import com.farriver.bwf.common.model.UploadTemplateData; import com.farriver.bwf.common.statics.LangConstants; import org.csource.common.NameValuePair; import org.csource.fastdfs.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.Objects; import java.util.Properties; @Service public class FastDFSService { private static final Logger logger = LoggerFactory.getLogger(FastDFSService.class); @Value("${file.nginx.host}") private String nginxHost; @Value("${file.nginx.port}") private String nginxPort; @Value("${fdfs.tracker_servers}") private String tracker_servers; @Value("${fdfs.connect_timeout_in_seconds}") private String connect_timeout_in_seconds; @Value("${fdfs.network_timeout_in_seconds}") private String network_timeout_in_seconds; @Value("${fdfs.charset}") private String charset; @Value("${fdfs.http_anti_steal_token}") private String http_anti_steal_token; @Value("${fdfs.http_secret_key}") private String http_secret_key; @Value("${fdfs.http_tracker_http_port}") private String http_tracker_http_port; @Value("${fdfs.connection_pool.enabled}") private String connection_pool_enabled; @Value("${fdfs.connection_pool.max_count_per_entry}") private String connection_pool_max_count_per_entry; @Value("${fdfs.connection_pool.max_idle_time}") private String connection_pool_max_idle_time; @Value("${fdfs.connection_pool.max_wait_time_in_ms}") private String connection_pool_max_wait_time_in_ms; private final TrackerServer trackerServer = null; private StorageClient1 storageClient = null; //让构造函数为 private,这样该类就不会被实例化 public FastDFSService getInstance() { try { if (storageClient == null) { Properties props = new Properties(); props.setProperty(ClientGlobal.PROP_KEY_TRACKER_SERVERS, tracker_servers); props.setProperty(ClientGlobal.PROP_KEY_CONNECT_TIMEOUT_IN_SECONDS, connect_timeout_in_seconds); props.setProperty(ClientGlobal.PROP_KEY_NETWORK_TIMEOUT_IN_SECONDS, network_timeout_in_seconds); props.setProperty(ClientGlobal.PROP_KEY_CHARSET, charset); props.setProperty(ClientGlobal.PROP_KEY_HTTP_ANTI_STEAL_TOKEN, http_anti_steal_token); props.setProperty(ClientGlobal.PROP_KEY_HTTP_SECRET_KEY, http_secret_key); props.setProperty(ClientGlobal.PROP_KEY_HTTP_TRACKER_HTTP_PORT, http_tracker_http_port); props.setProperty(ClientGlobal.PROP_KEY_CONNECTION_POOL_ENABLED, connection_pool_enabled); props.setProperty(ClientGlobal.PROP_KEY_CONNECTION_POOL_MAX_COUNT_PER_ENTRY, connection_pool_max_count_per_entry); props.setProperty(ClientGlobal.PROP_KEY_CONNECTION_POOL_MAX_IDLE_TIME, connection_pool_max_idle_time); props.setProperty(ClientGlobal.PROP_KEY_CONNECTION_POOL_MAX_WAIT_TIME_IN_MS, connection_pool_max_wait_time_in_ms); ClientGlobal.initByProperties(props); TrackerClient trackerClient = new TrackerClient(); TrackerServer trackerServer = trackerClient.getTrackerServer(); StorageServer storageServer = null; storageClient = new StorageClient1(trackerServer, storageServer); } } catch (Exception e) { logger.error(e.getMessage(), e); } return this; } private String uploadLocalFile(String localFileName, String extName, NameValuePair[] metas) throws Exception { return storageClient.upload_file1(localFileName, extName, metas); } private String uploadLocalFile(String localFileName) throws Exception { return uploadLocalFile(localFileName, null, null); } private String uploadLocalFile(String localFileName, String extName) throws Exception { return uploadLocalFile(localFileName, extName, null); } private String uploadFile(byte[] file, String fileName, long fileSize) throws Exception { NameValuePair[] metas = new NameValuePair[3]; metas[0] = new NameValuePair("fileName", fileName); metas[1] = new NameValuePair("fileSize", String.valueOf(fileSize)); return storageClient.upload_file1(file, fileName, metas); } private String uploadFile(byte[] fileContent, String extName, NameValuePair[] metas) throws Exception { return storageClient.upload_file1(fileContent, extName, metas); } private String uploadFile(byte[] fileContent) throws Exception { return uploadFile(fileContent, null, null); } private String uploadFile(MultipartFile file) throws Exception { if (file != null && !Objects.requireNonNull(file.getOriginalFilename()).isEmpty()) { String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); if (!fileSuffix.isEmpty()) { fileSuffix = fileSuffix.replace(".", ""); } return uploadFile(file.getBytes(), fileSuffix, null); } return null; } private String uploadFile(File file) throws Exception { if (file != null && !Objects.requireNonNull(file.getName()).isEmpty()) { String fileSuffix = file.getName().substring(file.getName().lastIndexOf(".")); if (!fileSuffix.isEmpty()) { fileSuffix = fileSuffix.replace(".", ""); } var fm = new FileInputStream(file); return uploadFile(fm.readAllBytes(), fileSuffix, null); } return null; } private String uploadFile(byte[] fileContent, String extName) throws Exception { return uploadFile(fileContent, extName, null); } //关闭资源 private void close() throws Exception { trackerServer.getConnection().close(); } private InputStream downloadFileStream(String groupName, String remoteFileName) throws Exception { byte[] fileByte = storageClient.download_file(groupName, remoteFileName); return new ByteArrayInputStream(fileByte); } private InputStream downloadFileStream(String file_id) throws Exception { byte[] fileByte = storageClient.download_file1(file_id); return new ByteArrayInputStream(fileByte); } private byte[] downloadFileBytes(String groupName, String remoteFileName) throws Exception { return storageClient.download_file(groupName, remoteFileName); } private byte[] downloadFileBytes(String file_id) throws Exception { return storageClient.download_file1(file_id); } private int deleteFile(String group, String fileName) throws Exception { return storageClient.delete_file(group, fileName); } private int deleteFile(String file_id) throws Exception { return storageClient.delete_file1(file_id); } private FileInfo queryFile(String group, String fileName) throws Exception { return storageClient.query_file_info(group, fileName); } private FileInfo queryFile(String file_id) throws Exception { return storageClient.query_file_info1(file_id); } private String getAccessBase() { if (nginxHost.toLowerCase().startsWith("https://")) { return String.format("%s", nginxHost); } else { if (nginxPort.isEmpty() || nginxPort.trim().isEmpty() || nginxPort.trim().equals("80")) { return String.format("%s", nginxHost); } else { return String.format("%s:%s", nginxHost, nginxPort); } } } public ApiData Upload(MultipartFile file) { String fileUrl = null; try { fileUrl = getInstance().uploadFile(file); var linkUrl = String.format("%s/%s", getAccessBase(), fileUrl); var data = new UploadTemplateData(); data.setLinkurl(linkUrl); data.setRelativepath(fileUrl); return ApiData.ok(LangConstants.MSG_INFO_SUCCESS, data); } catch (Exception ex) { logger.error(ex.getMessage(), ex); } return ApiData.error(LangConstants.MSG_ERROR_PARAMETERS); } public ApiData UploadFile(File file) { String fileUrl = null; try { fileUrl = getInstance().uploadFile(file); var linkUrl = String.format("%s/%s", getAccessBase(), fileUrl); var data = new UploadTemplateData(); data.setLinkurl(linkUrl); data.setRelativepath(fileUrl); return ApiData.ok(LangConstants.MSG_INFO_SUCCESS, data); } catch (Exception ex) { logger.error(ex.getMessage(), ex); } return ApiData.error(LangConstants.MSG_ERROR_PARAMETERS); } public ResponseEntity Download(String filepath) throws Exception { String[] paths = filepath.split("/"); String groupName = null; for (String item : paths) { if (item.indexOf("group") != -1) { groupName = item; break; } } String path = filepath.substring(filepath.indexOf(groupName) + groupName.length() + 1, filepath.length()); InputStream input = getInstance().downloadFileStream(groupName, path); //根据文件名获取 MIME 类型 String fileName = paths[paths.length - 1]; // wKgIZVzZEF2ATP08ABC9j8AnNSs744.jpg var headers = new HttpHeaders(); headers.setContentDispositionFormData("attachment", new String((fileName).getBytes("UTF-8"), "ISO-8859-1")); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity(input.readAllBytes(), headers, HttpStatus.CREATED); } public InputStream DownloadFile(String groupName, String remoteFileName) throws Exception { return getInstance().downloadFileStream(groupName, remoteFileName); } public ApiData Delete(String filepath) { try { getInstance().deleteFile(filepath); return ApiData.ok(LangConstants.MSG_INFO_SUCCESS); } catch (Exception e) { logger.error(e.getMessage(), e); } return ApiData.error(LangConstants.MSG_ERROR_PARAMETERS); } }