并没有改太多的核心实现,实在把很多无用的import去掉了,把Test类给去掉了,把读取配置类重新实现了。使用起来就很简单了,提供一个UTIL类的实现代码
/** * * * @ClassName: FastDFSUtil * @Description: TODO( FastDfs 操作工具类) * @author LiuYi * @date 2014年6月5日 下午4:39:19 * */ public class FastDFSUtil { private static final FastDFSUtil fastDFSUtil = new FastDFSUtil(); private static boolean isInit = true; public static final FastDFSUtil getInstance() { return fastDFSUtil; } static{ try { PropertiesLoader pl = SpringContextHolder.getBean(PropertiesLoader.class); DFSCustomIdClient.init(pl.getProperty("dfs"), pl.getProperty("dht")); } catch (Exception e) { e.printStackTrace(); } } public static DFSCustomIdClient getClient(String fdhtNamespace) { if(isInit){ getInstance(); isInit = false; } try { return new DFSCustomIdClient(fdhtNamespace); } catch (MyException e) { e.printStackTrace(); } return null; } /** * * @Description: TODO(上传文件到FastDFS) * @author LiuYi * @date 2014年6月5日 下午4:33:39 * @param fileName * 自定义的文件名 * @param file * 文件 * @param suffix * 后缀名 * @return * @throws IOException * @throws Exception * String */ public static String upFile(String fileName, File file, String suffix) throws IOException, Exception { DFSCustomIdClient client = getClient("seafood"); try { client.uploadFile(fileName, FileUtils.readFileToByteArray(file), suffix); return fileName + "." + suffix; } catch (Exception e) { throw e; } finally { client.close(); } } /** * * @Description: TODO(根据当前年与日生成文件名如 * /2014041806/akdhfajhfdabfdjahfdjafda.png) * @author LiuYi * @date 2014年6月5日 下午4:34:55 * @param file * @param suffix * @return * @throws IOException * @throws Exception * String */ public static String upFile(File file, String suffix) throws IOException, Exception { DFSCustomIdClient client = getClient("seafood"); try { Calendar cal = Calendar.getInstance();// 使用日历类 int year = cal.get(Calendar.YEAR);// 得到年 int month = cal.get(Calendar.MONTH) + 1;// 得到月,因为从0开始的,所以要加1 int day = cal.get(Calendar.DAY_OF_MONTH);// 得到天 int hour = cal.get(Calendar.HOUR);// 得到小时 int minute = cal.get(Calendar.MINUTE);// 得到分钟 StringBuffer buffer = new StringBuffer("/").append(year).append(month).append(day).append(hour) .append(minute).append("/").append(UUID.randomUUID().toString()); client.uploadFile(buffer.toString(), FileUtils.readFileToByteArray(file), suffix); return buffer.toString() + "." + suffix; } catch (Exception e) { throw e; } finally { if (client != null) client.close(); } } /** * * @Description: TODO(通过DB中的URL 获取到真正的在FastDFS上的URL) * @author LiuYi * @date 2014年6月5日 下午5:29:29 * @param dbUrl * @return String */ public static String dbImgUrl2FdfsUrl(String dbUrl){ DFSCustomIdClient client = getClient("seafood"); try { return client.getFdfsFileId(dbUrl); } catch (Exception e) { e.printStackTrace(); }finally{ if(client!=null){ client.close(); } } return dbUrl; } }
附上源码