package com.fsk.fsksystem.util; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Date; import org.apache.commons.lang3.StringUtils; import org.springframework.web.multipart.MultipartFile; import com.aliyun.oss.OSSClient; import com.aliyun.oss.model.BucketInfo; public class OssUtil { private static String endpoint = Constant.endpoint; private static String accessKeyId = Constant.accessKeyId; private static String accessKeySecret = Constant.accessKeySecret; private static String bucketName = Constant.bucketName; /** * 判断是否存在bucketName * @return */ private static boolean hasBucket(OSSClient ossClient){ return ossClient.doesBucketExist(bucketName); } /** * 创建bucket实例 */ private static void creatBucket(OSSClient ossClient){ if(!hasBucket(ossClient)) ossClient.createBucket(bucketName); } /** * 获取ossClient * @return */ public static OSSClient ossClientInitialization(){ return new OSSClient(endpoint, accessKeyId, accessKeySecret); } /** * 释放ossClient资源 */ private static void ossClientRelease(OSSClient ossClient){ ossClient.shutdown(); } /** * 获取bucket信息 */ private BucketInfo getBucketInfo(OSSClient ossClient){ return ossClient.getBucketInfo(bucketName); } /** * 文件上传并返回文件路径 * @param fileName * @return * @throws IOException */ public static String fileUpload(MultipartFile file) throws IOException{ OSSClient ossClient = ossClientInitialization(); creatBucket(ossClient); String fileName = getFileName(file.getOriginalFilename()); // 上传文件流 InputStream inputStream = file.getInputStream(); ossClient.putObject(bucketName, fileName, inputStream); String url = getUrl(ossClient,fileName); ossClientRelease(ossClient); return url; } /** * 获取附件上传保存到服务器的名称 * @param fileName 文件原始名称 * @return */ public static String getFileName(String fileName){ if(StringUtils.isBlank(fileName)){ return null; } if(fileName.lastIndexOf(".")>-1){ fileName = fileName.substring(fileName.lastIndexOf(".")).toLowerCase(); }else{ fileName = "."+fileName.toLowerCase(); } Date date = new Date(); long t = date.getTime(); date = null; return String.valueOf(t)+fileName; } /** * 获得url链接 * * @param fileName * @return */ public static String getUrl(OSSClient ossClient,String fileName) { // 设置URL过期时间为10年 3600l* 1000*24*365*10 Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10); // 生成URL URL url = ossClient.generatePresignedUrl(bucketName, fileName, expiration); if (url != null) { return url.toString(); } return null; } }