<!-- fastdfs start --> <dependency> <groupId>org.csource</groupId> <artifactId>fastdfs-client-java</artifactId> <version>1.25</version> </dependency> <!-- fastdfs end -->
<!-- fdfs文件系统相关配置 fdfs_client.conf--> <connect_timeout>2</connect_timeout> <network_timeout>30</network_timeout> <charset>UTF-8</charset> <tracker_server>172.23.27.120:22122</tracker_server> <http.anti_steal_token>no</http.anti_steal_token> <http.secret_key></http.secret_key> <http.tracker_http_port>8085</http.tracker_http_port> <!-- fdfs文件系统相关配置 -->
package com.curiousby.cn.util; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.springframework.web.multipart.MultipartFile; /** * * @author baoyou E-mail:curiousby@163.com * @version 2017年3月28日 下午3:09:56 * desc: */ public class FDFSFile { private String fileName; private String fileExt; private String fileSize; private byte[] content; public FDFSFile() { } public FDFSFile(String fileName, String fileExt, String fileSize, byte[] content) { this.fileName = fileName; this.fileExt = fileExt; this.fileSize = fileSize; this.content = content; } public FDFSFile(File file) { this.fileName = file.getName(); this.fileExt = FilenameUtils.getExtension(file.getName()); this.fileSize = String.valueOf(FileUtils.sizeOf(file)); try { this.content = FileUtils.readFileToByteArray(file); } catch (IOException e) { e.printStackTrace(); } } public FDFSFile(MultipartFile file) { this.fileName = file.getOriginalFilename(); this.fileExt = FilenameUtils.getExtension(file.getOriginalFilename()); this.fileSize = String.valueOf(file.getSize()); try { this.content = file.getBytes(); } catch (IOException e) { e.printStackTrace(); } } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getFileExt() { return fileExt; } public void setFileExt(String fileExt) { this.fileExt = fileExt; } public String getFileSize() { return fileSize; } public void setFileSize(String fileSize) { this.fileSize = fileSize; } public byte[] getContent() { return content; } public void setContent(byte[] content) { this.content = content; } }
package com.curiousby.cn.util; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; 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.TrackerServer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.web.multipart.MultipartFile; /** * * @author baoyou E-mail:curiousby@163.com * @version 2017年3月28日 下午3:09:51 * desc: */ public class FDFSUtil { private static Logger logger = LoggerFactory.getLogger(FDFSUtil.class); public static final String CLIENT_CONFIG_FILE = "fdfs_client.conf"; private static TrackerClient trackerClient; private static TrackerServer trackerServer; private static StorageServer storageServer; private static StorageClient1 storageClient; static { try { ClassPathResource cpr = new ClassPathResource(CLIENT_CONFIG_FILE); String fdfsConf = cpr.getFile().getAbsolutePath(); logger.info("----fdfsConf----" + fdfsConf); // 初始化fdfs全局配置 ClientGlobal.init(fdfsConf); trackerClient = new TrackerClient(); trackerServer = trackerClient.getConnection(); storageClient = new StorageClient1(trackerServer, storageServer); } catch (Exception e) { logger.error("FDFSUtil init------------", e); } } /** * * @param args */ public static void main(String[] args) { // 上传 File file = new File("C:\\Users\\cmcc-B100036\\Desktop\\截图\\fastdfs install monitor.png"); FDFSFile fdfsFile = new FDFSFile(file); String fileId = FDFSUtil.upload(fdfsFile); System.out.println(fdfsFile.getFileName()); System.out.println(fdfsFile.getFileExt()); System.out.println(fdfsFile.getFileSize()); // 下载 try { byte[] b = FDFSUtil.download(fileId); IOUtils.write(b, new FileOutputStream("C:\\Users\\cmcc-B100036\\Desktop\\aaa.png")); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // 删除 // int result = FDFSUtil.delete(fileId); } /** * @param file * @return */ public synchronized static String upload(FDFSFile file) { logger.info("File Name: {}; File Length: {}", file.getFileName(), file.getFileSize()); // 存储文件信息 NameValuePair[] metaList = new NameValuePair[3]; metaList[0] = new NameValuePair("fileName", file.getFileName()); metaList[1] = new NameValuePair("fileExt", file.getFileExt()); metaList[2] = new NameValuePair("fileSize", file.getFileSize()); long startTime = System.currentTimeMillis(); String uploadResult = null; try { uploadResult = storageClient.upload_file1(file.getContent(), file.getFileExt(), metaList); } catch (IOException e) { logger.error("IO Exception when uploadind the file: " + file.getFileName(), e); } catch (Exception e) { logger.error("Non IO Exception when uploadind the file: " + file.getFileName(), e); } logger.info("upload_file time used: " + (System.currentTimeMillis() - startTime) + " ms"); if (uploadResult == null) { logger.error("upload file fail, error code: " + storageClient.getErrorCode()); } logger.info("upload file successfully!!! " + "uploadResult: " + uploadResult); return uploadResult; } /** * @param mFiles * @return */ public static String upload(MultipartFile[] mFiles) { logger.info("upload MultipartFile[]: {}", mFiles.length); if (ArrayUtils.isEmpty(mFiles)) { return ""; } FDFSFile[] files = new FDFSFile[mFiles.length]; for (int i = 0; i < mFiles.length; i++) { files[i] = new FDFSFile(mFiles[i]); } return upload(files); } /** * @param files * @return */ public static String upload(FDFSFile[] files) { logger.info("upload FDFSFile[]: {}", files.length); String result = ""; for (FDFSFile fdfsFile : files) { result += upload(fdfsFile) + ","; } if (StringUtils.isNotEmpty(result)) { result = result.substring(0, result.length() - 1); } logger.info("upload FDFSFile[] result: {}", result); return result; } /** * 获取文件属性信息 * * @param fileId * 文件标识 * @return FDFSFile:文件名,后缀名,大小 */ public static FDFSFile getFileMeta(String fileId) { logger.info("fileId--" + fileId); FDFSFile fdfsFile = new FDFSFile(); try { NameValuePair[] nvps = storageClient.get_metadata1(fileId); if (nvps != null) { fdfsFile.setFileExt(nvps[0].getValue()); fdfsFile.setFileName(nvps[1].getValue()); fdfsFile.setFileSize(nvps[2].getValue()); } } catch (Exception e) { e.printStackTrace(); } logger.info("getFileMeta info success!"); return fdfsFile; } /** * 获取文件属性信息 * * @param fileIds * 多个文件标识,以,分隔 * @return FDFSFile[]:文件名,后缀名,大小 */ public static FDFSFile[] getFileMetas(String fileIds) { logger.info("fileIds--" + fileIds); if (StringUtils.isEmpty(fileIds)) { return null; } String[] fileId = fileIds.split(","); FDFSFile[] fdfsFiles = new FDFSFile[fileId.length]; for (int i = 0; i < fileId.length; i++) { fdfsFiles[i] = getFileMeta(fileId[i]); } return fdfsFiles; } /** * 下载文件 * * @param fileId * 文件标识 * @return byte[]文件内容 */ public static byte[] download(String fileId) { logger.info("fileId--" + fileId); byte[] b = null; try { b = storageClient.download_file1(fileId); } catch (Exception e) { e.printStackTrace(); } logger.info("download file successfully!!! " + System.currentTimeMillis()); return b; } /** * 删除文件 * * @param fileId * @return 0:成功 */ public static int delete(String fileId) { logger.info("fileId--" + fileId); int i = 1; try { i = storageClient.delete_file1(fileId); logger.info(i == 0 ? "删除成功" : "删除失败:" + i); } catch (Exception e) { e.printStackTrace(); } return i; } /** * 递归删除目录下的所有文件及子目录下所有文件 * @param dir 将要删除的文件目录 * @return boolean Returns "true" if all deletions were successful. * If a deletion fails, the method stops attempting to * delete and returns "false". */ public static boolean deleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); if (children != null) { //递归删除目录中的子目录下 for (int i = 0; i < children.length; i++) { boolean success = deleteDir(new File(dir, children[i])); if (!success) { return false; } } } } // 目录此时为空,可以删除 return dir.delete(); } }
捐助开发者
在兴趣的驱动下,写一个免费
的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(支持支付宝和微信捐助,加入it技术扣扣群),没钱捧个人场,谢谢各位。
谢谢您的赞助,我会做的更好!