上传图片到阿里云oss

1、加入依赖包
<dependency>
   <groupId>com.aliyun.oss</groupId>
   <artifactId>aliyun-sdk-oss</artifactId>
   <version>2.4.0</version>
</dependency>
<dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <version>1.18.4</version>
   <scope>provided</scope>
</dependency>

 

2.上传代码

// @Value("${aliyun.endpoint}")
  private String endpoint;//节点,在阿里云开通oss功能后获得
 // @Value("${aliyun.accessKeyId}")
  private String accessKeyId;//id,在阿里云开通oss功能后获得
 // @Value("${aliyun.accessKeySecret}")
  private String accessKeySecret;//秘钥,在阿里云开通oss功能后获得
//  @Value("${aliyun.bucketName}")
  private String bucketName ;//组名,在阿里云开通oss功能后创建

  //文件存储目录
  private String filedir = "userImg/";

 

  /**
   *
   * 上传图片
   * @param file
   * @return
   */
  public String uploadImg2Oss(String path,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,path);
          if (inputStream != null) {
              inputStream.close();
          }
          return name;//RestResultGenerator.createSuccessResult(name);
      } catch (Exception e) {
          return "上传失败";//RestResultGenerator.createErrorResult(ResponseEnum.PHOTO_UPLOAD);
      }
  }

  /**
   * 上传图片获取fileUrl
   * @param instream
   * @param fileName 文件名称
   * @param path 文件路径
   * @return
   */
  private String uploadFile2OSS(InputStream instream, String fileName,String path) {
      String ret = "";
      OSSClient ossClient = null;
      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 = new OSSClient(endpoint, accessKeyId, accessKeySecret);
          ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
          PutObjectResult putResult = ossClient.putObject(bucketName, path + fileName, instream, objectMetadata);
          ret = putResult.getETag();
      } catch (IOException e) {
          log.error(e.getMessage(), e);
      } finally {
          try {
              if (instream != null) {
                  instream.close();
              }
              //在ossClient使用之后应该立即关闭
              if(ossClient != null){
                  ossClient.shutdown();
              }

          } catch (IOException e) {
              e.printStackTrace();
          }
      }
      return ret;
  }
public void delete(String objectName) {
    OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    // 根据BucketName,objectName删除文件
    ossClient.deleteObject(bucketName, objectName);
    if(ossClient != null){
        ossClient.shutdown();
    }
}

/**
 * @author lastwhisper
 * @desc 下载文件
 * 文档链接 https://help.aliyun.com/document_detail/84823.html?spm=a2c4g.11186623.2.7.37836e84ZIuZaC#concept-84823-zh
 * @email gaojun56@163.com
 */
public void exportOssFile(OutputStream os, String objectName) throws IOException {
    OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
    OSSObject ossObject = ossClient.getObject(bucketName, objectName);
    // 读取文件内容。
    BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent());
    BufferedOutputStream out = new BufferedOutputStream(os);
    byte[] buffer = new byte[1024];
    int lenght = 0;
    while ((lenght = in.read(buffer)) != -1) {
        out.write(buffer, 0, lenght);
    }
    if(ossClient != null){
        ossClient.shutdown();
    }
    if (out != null) {
        out.flush();
        out.close();
    }
    if (in != null) {
        in.close();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值