【阿里OSS】java后台集成OSS的SDK之版本升级及工具封装
程序员文章站
2022-07-14 21:49:04
...
环境:
maven 3.0
jdk 1.8
原oss版本2.8.3
升级后为:3.5.0
pom依赖:
<!-- 阿里OSS --> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <!--<version>2.8.3</version>--> <version>3.5.0</version> </dependency>
配置文件添加:
# ======= 阿里OSS配置 ========= aliyun.OSS.endpoint=http://oss-cn-beijing.aliyuncs.com aliyun.OSS.accessKeyId= 自个的KEY aliyun.OSS.accessKeySecret= 同上 aliyun.OSS.bucketName=afinal2mc #自己定义的存储空间 aliyun.OSS.filedir=sys/ #自己在存储空间创建的文件夹 aliyun.OSS.fileMaxSize=10 #文件上传最大M数
封装util
import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.model.DeleteObjectsRequest; import com.aliyun.oss.model.DeleteObjectsResult; import com.aliyun.oss.model.ObjectMetadata; import com.aliyun.oss.model.PutObjectResult; import com.jeeplus.common.utils.DateUtils; import com.jeeplus.common.utils.PropertiesLoader; import com.jeeplus.common.utils.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import java.io.*; import java.net.URL; import java.util.Date; import java.util.List; /** * @ProjectName: Hematopathy * @Package: com.jeeplus.oss.utils * @ClassName: OSSUtil * @Author: MC * @Description: ${description} * @Date: 2019/11/16 0016 10:34 * @Version: 1.0 */ @Component public class OSSClientUtil { protected PropertiesLoader loader = new PropertiesLoader("jeeplus.properties"); //获取配置文件参数 Log log = LogFactory.getLog(OSSClientUtil.class); private String endpoint = loader.getProperty("aliyun.OSS.endpoint"); private String accessKeyId = loader.getProperty("aliyun.OSS.accessKeyId"); private String accessKeySecret = loader.getProperty("aliyun.OSS.accessKeySecret"); //空间 private String bucketName = loader.getProperty("aliyun.OSS.bucketName"); //文件存储目录 private String filedir = loader.getProperty("aliyun.OSS.filedir"); //上传最大限制 private int fileMaxSize = Integer.parseInt(loader.getProperty("aliyun.OSS.fileMaxSize")); public OSS getOssClient(){ return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); } /** * 销毁 */ public void destory(OSS ossClient) { ossClient.shutdown(); } /** * 上传图片 * * @param url */ public void uploadImg2Oss(String url,OSS ossClient) throws FileNotFoundException { File fileOnServer = new File(url); FileInputStream fin; fin = new FileInputStream(fileOnServer); String[] split = url.split("/"); this.uploadFile2OSS(fin, split[split.length - 1],ossClient); } public String uploadImg2Oss(MultipartFile file,OSS ossClient) throws IOException { if (file.getSize() > 1024 * 1024 * fileMaxSize) { throw new IOException("上传图片大小不能超过"+fileMaxSize+"M!"); } String originalFilename = file.getOriginalFilename(); String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase(); Date now = new Date(); String nowStr = DateUtils.formatDateTime(now); String name = nowStr.replace(" ","MC") + substring; InputStream inputStream = file.getInputStream(); this.uploadFile2OSS(inputStream, name,ossClient); return name; } /** * 获得图片路径 * * @param fileUrl * @return */ public String getImgUrl(String fileUrl,OSS ossClient) { if (!StringUtils.isEmpty(fileUrl)) { String[] split = fileUrl.split("/"); return this.getUrl(this.filedir + split[split.length - 1],ossClient); } return null; } /** * 上传到OSS服务器 如果同名文件会覆盖服务器上的 * * @param instream 文件流 * @param fileName 文件名称 包括后缀名 * @return 出错返回"" ,唯一MD5数字签名 */ public String uploadFile2OSS(InputStream instream, String fileName,OSS ossClient) { String ret = ""; try { //创建上传Object的Metadata ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setContentLength(instream.available()); objectMetadata.setCacheControl("no-cache"); objectMetadata.setHeader("Pragma", "no-cache"); objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf(".")))); objectMetadata.setContentDisposition("inline;filename=" + fileName); //上传文件 PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata); ret = putResult.getETag(); } catch (IOException e) { log.error(e.getMessage(), e); } finally { try { if (instream != null) { instream.close(); } } catch (IOException e) { e.printStackTrace(); } } return ret; } /** * Description: 判断OSS服务文件上传时文件的contentType * * @param FilenameExtension 文件后缀 * @return String */ public static String getcontentType(String FilenameExtension) { if (FilenameExtension.equalsIgnoreCase(".bmp")) { return "image/bmp"; } if (FilenameExtension.equalsIgnoreCase(".gif")) { return "image/gif"; } if (FilenameExtension.equalsIgnoreCase(".jpeg") || FilenameExtension.equalsIgnoreCase(".jpg") || FilenameExtension.equalsIgnoreCase(".png")) { return "image/jpeg"; } if (FilenameExtension.equalsIgnoreCase(".html")) { return "text/html"; } if (FilenameExtension.equalsIgnoreCase(".txt")) { return "text/plain"; } if (FilenameExtension.equalsIgnoreCase(".vsd")) { return "application/vnd.visio"; } if (FilenameExtension.equalsIgnoreCase(".pptx") || FilenameExtension.equalsIgnoreCase(".ppt")) { return "application/vnd.ms-powerpoint"; } if (FilenameExtension.equalsIgnoreCase(".docx") || FilenameExtension.equalsIgnoreCase(".doc")) { return "application/msword"; } if (FilenameExtension.equalsIgnoreCase(".xml")) { return "text/xml"; } return "image/jpeg"; } /** * 获得url链接 * * @param key * @return */ public String getUrl(String key,OSS ossClient) { // 设置URL过期时间为10年 3600l* 1000*24*365*10 Date nowDate = new Date(); long time = nowDate.getTime(); Date expiration = new Date( time + 3600L * 1000 * 24 * 365 * 10); // 生成URL URL url = ossClient.generatePresignedUrl(bucketName, key, expiration); if (url != null) { return url.toString(); } return null; } /** * 删除某个Object * http://127.0.0.1:8080/a/oss/del?url= sys/2019-11-16MC11:34:52.png * @param bucketUrl * @return */ public boolean deleteObject(String bucketUrl,OSS ossClient) { try { boolean b = ossClient.doesObjectExist(bucketName, bucketUrl); System.out.println("删除文件的调用结果:"+b + "================================="); // 删除Object. ossClient.deleteObject(bucketName, bucketUrl); } catch (Exception e) { e.printStackTrace(); return false; } finally { this.destory(ossClient); } return true; } /** * 删除多个Object * * @param bucketUrls * @return */ public boolean deleteObjects(List<String> bucketUrls,OSS ossClient) { try { // 删除Object. DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(bucketUrls)); List<String> deletedObjects = deleteObjectsResult.getDeletedObjects(); } catch (Exception e) { e.printStackTrace(); return false; } finally { this.destory(ossClient); } return true; } }
注意:2.0+使用的是OSSClient对象,而3.0+使用的是OSS对象。
创建方式也不一样,一个是newOSSClient一个是通过Builder对象获取
附带的日期工具类:
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.apache.commons.lang3.time.DateFormatUtils; /** * 日期工具类, 继承org.apache.commons.lang.time.DateUtils类 * * @author jeeplus * @version 2014-4-15 */ public class DateUtils extends org.apache.commons.lang3.time.DateUtils { public static final String PATTERN_STANDARD = "yyyy-MM-dd HH:mm:ss"; public static final String PATTERN_DATE = "yyyy-MM-dd"; public static final String PARRERN_Hour_Minute = "HH:mm"; private static String[] parsePatterns = { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM" }; /** * 得到几天前的时间 * * @param d * @param day * @return */ public static Date getDateBefore(Date d, int day) { Calendar no = Calendar.getInstance(); no.setTime(d); no.set(Calendar.DATE, no.get(Calendar.DATE) - day); return no.getTime(); } /** * 得到当前日期字符串 格式(yyyy-MM-dd) */ public static String getDate() { return getDate("yyyy-MM-dd"); } /** * 得到当前日期字符串 格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E" */ public static String getDate(String pattern) { return DateFormatUtils.format(new Date(), pattern); } /** * 得到日期字符串 默认格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E" */ public static String formatDate(Date date, Object... pattern) { String formatDate = null; if (pattern != null && pattern.length > 0) { formatDate = DateFormatUtils.format(date, pattern[0].toString()); } else { formatDate = DateFormatUtils.format(date, "yyyy-MM-dd"); } return formatDate; } /** * 得到日期时间字符串,转换格式(yyyy-MM-dd HH:mm:ss) */ public static String formatDateTime(Date date) { return formatDate(date, "yyyy-MM-dd HH:mm:ss"); } /** * 得到当前时间字符串 格式(HH:mm:ss) */ public static String getTime() { return formatDate(new Date(), "HH:mm:ss"); } /** * 得到当前日期和时间字符串 格式(yyyy-MM-dd HH:mm:ss) */ public static String getDateTime() { return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"); } /** * 得到当前年份字符串 格式(yyyy) */ public static String getYear() { return formatDate(new Date(), "yyyy"); } /** * 得到当前月份字符串 格式(MM) */ public static String getMonth() { return formatDate(new Date(), "MM"); } /** * 得到当天字符串 格式(dd) */ public static String getDay() { return formatDate(new Date(), "dd"); } /** * 得到当前星期字符串 格式(E)星期几 */ public static String getWeek() { return formatDate(new Date(), "E"); } public static int getWeekInt(){ String week = getWeek(); week = week.substring(week.length()-1, week.length()); int weekInt = 0; if(week.equals("一")){ return weekInt = 1; }else if(week.equals("二")){ return weekInt = 2; }else if(week.equals("三")){ return weekInt = 3; }else if(week.equals("四")){ return weekInt = 4; }else if(week.equals("五")){ return weekInt = 5; }else if(week.equals("六")){ return weekInt = 6; }else { return weekInt = 7; } } /** * 日期型字符串转化为日期 格式 { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", * "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy.MM.dd", * "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" } */ public static Date parseDate(Object str) { if (str == null) { return null; } try { return parseDate(str.toString(), parsePatterns); } catch (ParseException e) { return null; } } /** * 获取过去的天数 * * @param date * @return */ public static long pastDays(Date date) { long t = System.currentTimeMillis() - date.getTime(); return t / (24 * 60 * 60 * 1000); } /** * 获取过去的小时 * * @param date * @return */ public static long pastHour(Date date) { long t = System.currentTimeMillis() - date.getTime(); return t / (60 * 60 * 1000); } /** * 获取过去的分钟 * * @param date * @return */ public static long pastMinutes(Date date) { long t = System.currentTimeMillis() - date.getTime(); return t / (60 * 1000); } /** * 转换为时间(天,时:分:秒.毫秒) * * @param timeMillis * @return */ public static String formatDateTime(long timeMillis) { long day = timeMillis / (24 * 60 * 60 * 1000); long hour = (timeMillis / (60 * 60 * 1000) - day * 24); long min = ((timeMillis / (60 * 1000)) - day * 24 * 60 - hour * 60); long s = (timeMillis / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60); long sss = (timeMillis - day * 24 * 60 * 60 * 1000 - hour * 60 * 60 * 1000 - min * 60 * 1000 - s * 1000); return (day > 0 ? day + "," : "") + hour + ":" + min + ":" + s + "." + sss; } /** * 获取两个日期之间的天数 * * @param before * @param after * @return */ public static int getDistanceOfTwoDate(Date before, Date after) { long beforeTime = before.getTime(); long afterTime = after.getTime(); return (int) ((afterTime - beforeTime) / (1000 * 60 * 60 * 24)); } /** * 字符串转日期 * * @param strDate * 字符串日期 * @param pattern * 需要转换成的类型(YYYY-mm-dd) * @return */ public static Date string2Date(String strDate, String pattern) { if (strDate == null || strDate.equals("")) { throw new RuntimeException("str date null"); } if (pattern == null || pattern.equals("")) { pattern = DateUtils.PATTERN_DATE; } SimpleDateFormat sdf = new SimpleDateFormat(pattern); Date date = null; try { date = sdf.parse(strDate); } catch (ParseException e) { throw new RuntimeException(e); } return date; } //根据给定的时间算出间隔天数 public static String getBetweenDay(Date startDate,Date endDate){ long res=endDate.getTime()-startDate.getTime(); res=res/24/60/60/1000; return Long.toString(res); } //获取距今7天每天的日期,转换成string public static List<String> getDateStringList(){ long time=86400000; Date date=new Date(); List<String> list=new ArrayList<String>(); for (int i = 6; i >0 ; i--) { Date date2=new Date(); long t=date.getTime()-time*i; date2.setTime(t); list.add(DateUtils.formatDateTime(date2)); } list.add(DateUtils.formatDateTime(date)); return list; } public static List<Date> getDateList(Date before, Date after, String str,String medicine_cycle) { long frequency=1; if ("medicine_cycle01".equals(medicine_cycle)) { frequency=1; }else if("medicine_cycle02".equals(medicine_cycle)){ frequency=2; }else if("medicine_cycle03".equals(medicine_cycle)){ frequency=3; }else if("medicine_cycle04".equals(medicine_cycle)){ frequency=7; }else if("medicine_cycle05".equals(medicine_cycle)){ frequency=14; }else if("medicine_cycle06".equals(medicine_cycle)){ frequency=30; } List<Date> dates = new ArrayList<Date>(); long beforeTime = before.getTime(); long afterTime = after.getTime(); long day=1000 * 60 * 60 * 24*frequency; int days = (int) ((afterTime - beforeTime) / (1000 * 60 * 60 * 24*frequency)); if (days>0) { for (int i = 0; i <=days; i++) { if (null != str && !"".equals(str)) { if (str.contains(";")) { String[] strings = str.split(";"); for (String string : strings) { if (string.contains(":")) { String[] strings2 = string.split(":"); Integer hour = Integer.parseInt(strings2[0]); Integer min = Integer.parseInt(strings2[1]); long time = 1000 * 60 * 60 * hour + 1000 * 60 * min; Date date=new Date(); if (i==0) { date.setTime(beforeTime+time); dates.add(date); }else { beforeTime=beforeTime+day; date.setTime(beforeTime+time); dates.add(date); } } else if (string.contains(":")) { String[] strings2 = string.split(":"); Integer hour = Integer.parseInt(strings2[0]); Integer min = Integer.parseInt(strings2[1]); long time = 1000 * 60 * 60 * hour + 1000 * 60 * min; Date date=new Date(); if (i==0) { date.setTime(beforeTime+time); dates.add(date); }else{ beforeTime=beforeTime+day; date.setTime(beforeTime+time); dates.add(date); } } } } else { if (str.contains(":")) { String[] strings2 = str.split(":"); Integer hour = Integer.parseInt(strings2[0]); Integer min = Integer.parseInt(strings2[1]); long time = 1000 * 60 * 60 * hour + 1000 * 60 * min; Date date=new Date(); if (i==0) { date.setTime(beforeTime+time); dates.add(date); }else{ beforeTime=beforeTime+day; date.setTime(beforeTime+time); dates.add(date); } } else if (str.contains(":")) { String[] strings2 = str.split(":"); Integer hour = Integer.parseInt(strings2[0]); Integer min = Integer.parseInt(strings2[1]); long time = 1000 * 60 * 60 * hour + 1000 * 60 * min; Date date=new Date(); if (i==0) { date.setTime(beforeTime+time); dates.add(date); }else{ beforeTime=beforeTime+day; date.setTime(beforeTime+time); dates.add(date); } } } } } }else{ if (null != str && !"".equals(str)) { if (str.contains(";")) { String[] strings = str.split(";"); for (String string : strings) { if (string.contains(":")) { String[] strings2 = string.split(":"); Integer hour = Integer.parseInt(strings2[0]); Integer min = Integer.parseInt(strings2[1]); long time = 1000 * 60 * 60 * hour + 1000 * 60 * min; Date date=new Date(); date.setTime(beforeTime+time); dates.add(date); } else if (string.contains(":")) { String[] strings2 = string.split(":"); Integer hour = Integer.parseInt(strings2[0]); Integer min = Integer.parseInt(strings2[1]); long time = 1000 * 60 * 60 * hour + 1000 * 60 * min; Date date=new Date(); date.setTime(beforeTime+time); dates.add(date); } } } else { if (str.contains(":")) { String[] strings2 = str.split(":"); Integer hour = Integer.parseInt(strings2[0]); Integer min = Integer.parseInt(strings2[1]); long time = 1000 * 60 * 60 * hour + 1000 * 60 * min; Date date=new Date(); date.setTime(beforeTime+time); dates.add(date); } else if (str.contains(":")) { String[] strings2 = str.split(":"); Integer hour = Integer.parseInt(strings2[0]); Integer min = Integer.parseInt(strings2[1]); long time = 1000 * 60 * 60 * hour + 1000 * 60 * min; Date date=new Date(); dates.add(date); } } } } return dates; } /** * date 转 String * @param date * @return */ public static String dateToString(Date date){ SimpleDateFormat sdf = new SimpleDateFormat(PATTERN_DATE); return sdf.format(date); } public static String dateToStringYMDHMS(Date date){ SimpleDateFormat sdf = new SimpleDateFormat(PATTERN_STANDARD); return sdf.format(date); } public static String dateToStringYMDHM(Date date){ SimpleDateFormat sdf = new SimpleDateFormat(PATTERN_DATE + " " +PARRERN_Hour_Minute); return sdf.format(date); } public static Date stringToDateYMDHMS(String str) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat(PATTERN_STANDARD); return sdf.parse(str); } public static Date stringToDateYMD(String str) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat(PATTERN_DATE); return sdf.parse(str); } /** * CTS转UTC时间(加8小时) * @param date * @return */ public static Date CTSToUTC(Date date){ //8小时误差修正 long l=28800000L; date.setTime(date.getTime()+l); return date; } public static boolean isDateString(String datevalue, String dateFormat) { if (StringUtils.isEmpty(datevalue) || StringUtils.isEmpty(dateFormat)) { return false; } try { SimpleDateFormat fmt = new SimpleDateFormat(dateFormat); java.util.Date dd = fmt.parse(datevalue); if (datevalue.equals(fmt.format(dd))) { return true; } else { return false; } } catch (Exception e) { return false; } } public static int compare_date(String DATE1, String DATE2) { SimpleDateFormat df = new SimpleDateFormat(PATTERN_STANDARD); try { Date dt1 = df.parse(DATE1); Date dt2 = df.parse(DATE2); if (dt1.getTime() > dt2.getTime()) { // System.out.println("dt1 在dt2前"); return 1; } else if (dt1.getTime() < dt2.getTime()) { // System.out.println("dt1在dt2后"); return -1; } else { return 0; } } catch (Exception exception) { exception.printStackTrace(); } return 0; } public static int compare_date(String DATE1, String DATE2,String foramt) { SimpleDateFormat df = new SimpleDateFormat(foramt); try { Date dt1 = df.parse(DATE1); Date dt2 = df.parse(DATE2); if (dt1.getTime() > dt2.getTime()) { // System.out.println("dt1 在dt2前"); return 1; } else if (dt1.getTime() < dt2.getTime()) { // System.out.println("dt1在dt2后"); return -1; } else { return 0; } } catch (Exception exception) { exception.printStackTrace(); } return 0; } public static String getYesterday(){ SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date=new Date(); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.DAY_OF_MONTH, -1); date = calendar.getTime(); return sdf.format(date); } }
控制器调用:
@Controller @RequestMapping(value = "${adminPath}/oss") public class OSSController { @Autowired private OSSClientUtil ossClientUtil; //这个是上传后直接获取外网连接地址的,个人觉得还是很方便的 @RequestMapping("uploadImg1") @ResponseBody public String uploadImg1(@RequestParam(value = "file", required = false) MultipartFile imgFile) throws IOException { OSS ossClient = ossClientUtil.getOssClient(); String name = ossClientUtil.uploadImg2Oss(imgFile,ossClient); String imgUrl = ossClientUtil.getImgUrl(name,ossClient); ossClientUtil.destory(ossClient); return imgUrl; } }
上一篇: Flink Hudi 测试
下一篇: 最近公司培训的算法