利用阿里云OSS对文件进行存储,上传等操作

 
--pom.xml加入阿里OSS存储依赖
<!--阿里云OSS存储-->
<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>2.8.3</version>
</dependency>

--配置阿里云oss相关常量参数
/** @Author: xxxx   @Description: ${description} 阿里云 constant @Date: 2020/11/26 14:15 */
public class AliyunOSSConfigConstant {
  // 私有构造方法 禁止该类初始化
  private AliyunOSSConfigConstant() {}
  // 仓库名称
  public static final String BUCKET_NAME ="your backetname";
  // 地域节点
  public static final String END_POINT ="your endpoint address";
  // AccessKey ID 阿里云AccessKey
  public static final String AccessKey_ID ="your accesskeyid";
  // Access Key Secret 阿里云Secret
  public static final String AccessKey_Secret ="your acesskeySecret";
}

 

--编写操作oss的工具类
/** @Author: xxxx  @Description: ${description}阿里云OSS工具类 @Date: 2020/11/26 14:13 */
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import com.stdl.chargingpile.config.constant.Constants;
import com.stdl.chargingpile.service.OrderService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Random;

public class AliyunOSSUtil {
  @Autowired private OrderService orderService2;
  String  filedir="img/";
  private static final Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);
  /**
   * 删除一个Bucket和其中的Objects
   *
   * @param client
   * @param bucketName
   * @throws OSSException
   * @throws ClientException
   */
  public static void deleteBucket(OSSClient client, String bucketName)
      throws OSSException, ClientException {

    ObjectListing ObjectListing = client.listObjects(bucketName);
    List<OSSObjectSummary> listDeletes = ObjectListing.getObjectSummaries();
    for (int i = 0; i < listDeletes.size(); i++) {
      String objectName = listDeletes.get(i).getKey();
      // 如果不为空,先删除bucket下的文件
      client.deleteObject(bucketName, objectName);
    }
    client.deleteBucket(bucketName);
  }

  /**
   * 把Bucket设置为所有人可读
   *
   * @param client
   * @param bucketName
   * @throws OSSException
   * @throws ClientException
   */
  public static void setBucketPublicReadable(OSSClient client, String bucketName)
      throws OSSException, ClientException {
    // 创建bucket
    client.createBucket(bucketName);

    // 设置bucket的访问权限,public-read-write权限
    client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
  }

  /**
   * 上传文件
   *
   * @param client
   * @param bucketName
   * @param key
   * @param filename
   * @param contentType default "image/gif"
   * @throws OSSException
   * @throws ClientException
   * @throws FileNotFoundException
   */
  public static String uploadFile(
      OSSClient client, String bucketName, String key, String filename, String contentType)
      throws OSSException, ClientException, FileNotFoundException {
    File file = new File(filename);
    contentType = contentType == null ? "image/gif" : contentType;
    ObjectMetadata objectMeta = new ObjectMetadata();
    objectMeta.setContentLength(file.length());
    objectMeta.setContentType(contentType);
    InputStream input = new FileInputStream(file);
    PutObjectResult result = client.putObject(bucketName, key, input, objectMeta);
    return result.getETag();
  }

  /**
   * 下载文件
   *
   * @param client
   * @param bucketName
   * @param key
   * @param filename
   * @throws OSSException
   * @throws ClientException
   */
  public static void downloadFile(OSSClient client, String bucketName, String key, String filename)
      throws OSSException, ClientException {
    client.getObject(new GetObjectRequest(bucketName, key), new File(filename));
  }

  /**
   * 创建一个文件夹
   *
   * @param client
   * @param bucketName
   * @param folderPah
   */
  public static void createFolder(OSSClient client, String bucketName, String folderPah) {
    ObjectMetadata objectMeta = new ObjectMetadata();
    byte[] buffer = new byte[0];
    ByteArrayInputStream in = new ByteArrayInputStream(buffer);
    objectMeta.setContentLength(0);
    try {
      client.putObject(bucketName, folderPah, in, objectMeta);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        in.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

  /**
   * 删除一个OSS文件对象
   *
   * @param client
   * @param bucketName
   * @param key
   */
  public static void deleteObject(OSSClient client, String bucketName, String key) {
    client.deleteObject(bucketName, key);
  }

  public  static String  reFundPath(String mechNo){
    String certpath = TMP_DIR  + File.separator + mechNo;
      boolean dirs = createDir(certpath);
      if(dirs==true){
      OSSClient client =
          new OSSClient(Constants.endpoint, accessKeyId, accessKeySecret);
      downloadFile(
          client,
          Constants.bucket,
          mechNo+"/apiclient_cert.p12",
          certpath + File.separator + "apiclient_cert.p12");
      }
    System.out.println(certpath + File.separator + "apiclient_cert.p12");
      return certpath;
  }


  /**
   * 获取系统临时目录
   */
  private static final String TMP_DIR= System.getProperty("java.io.tmpdir");


  public static boolean createDir(String destDirName) {
    File dir = new File(destDirName);
    if (dir.exists()) {
      System.out.println("创建目录" + destDirName + "目标目录已经存在,无需重新创建");
      return true;
    }
    if (!destDirName.endsWith(File.separator)) {
      destDirName = destDirName + File.separator;
    }
    // 创建目录
    if (dir.mkdirs()) {
      System.out.println("创建目录" + destDirName + "成功!");
      return true;
    } else {
      System.out.println("创建目录" + destDirName + "失败!");
      return false;
    }
  }


  /**
   *
   * 上传图片
   * @param file
   * @return
   */
  public String uploadImg2Oss(MultipartFile file) {
    if (file.getSize() > 1024 * 1024 *20) {
      return "图片太大";//RestResultGenerator.createErrorResult(ResponseEnum.PHOTO_TOO_MAX);
    }
    String originalFilename = file.getOriginalFilename();
    String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
    Random random = new Random();
    String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
    try {
      InputStream inputStream = file.getInputStream();
      this.uploadFile2OSS(inputStream, name);
      return name;//RestResultGenerator.createSuccessResult(name);
    } catch (Exception e) {
      return "上传失败";//RestResultGenerator.createErrorResult(ResponseEnum.PHOTO_UPLOAD);
    }
  }

  /**
   * 上传图片获取fileUrl
   * @param instream
   * @param fileName
   * @return
   */
  private String uploadFile2OSS(InputStream instream, String fileName) {
    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);
      //上传文件

      OSSClient ossClient = new OSSClient(Constants.endpoint, accessKeyId, accessKeySecret);
      PutObjectResult putResult = ossClient.putObject(bucket, filedir + fileName, instream, objectMetadata);
      ret = putResult.getETag();
    } catch (IOException e) {
      logger.error(e.getMessage(), e);
    } finally {
      try {
        if (instream != null) {
          instream.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return ret;
  }

  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/jpg";
    }
    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/jpg";
  }

  /**
   * 获取图片路径
   * @param fileUrl
   * @return
   */
  public String getImgUrl(String fileUrl) {
    if (!StringUtils.isEmpty(fileUrl)) {
      String[] split = fileUrl.split("/");
      String url = this.getUrl(this.filedir + split[split.length - 1]);
      return url;
    }
    return null;
  }

  /**
   * 获得url链接
   *
   * @param key
   * @return
   */
  public String getUrl(String key) {
    // 设置URL过期时间为10年 3600l* 1000*24*365*10
    Date expiration = new Date(new Date().getTime() + 3600L * 1000 * 24 * 365 * 10);
    // 生成URL
    OSSClient ossClient = new OSSClient(Constants.endpoint, accessKeyId, accessKeySecret);
    URL url = ossClient.generatePresignedUrl(bucket, key, expiration);
    if (url != null) {
      return url.toString();
    }
    return null;
  }


  /**
   * 多图片上传
   * @param fileList
   * @return
   */
  public String checkList(List<MultipartFile> fileList) {
    String fileUrl = "";
    String str = "";
    String photoUrl = "";
    for(int i = 0;i< fileList.size();i++){
      fileUrl = uploadImg2Oss(fileList.get(i));
      str = getImgUrl(fileUrl);
      if(i == 0){
        photoUrl = str;
      }else {
        photoUrl += "," + str;
      }
    }
    return photoUrl.trim();
  }

  /**
   * 单个图片上传
   * @param file
   * @return
   */
  public String checkImage(MultipartFile file){
    String fileUrl = uploadImg2Oss(file);
    String str = getImgUrl(fileUrl);
    return str.trim();
  }
}

 

以上就是操作阿里OSS的相关方法,供大家学习参考交流~!

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值