阿里云oss服务 *** 作文件,上传下载生成链接删除通知等

阿里云oss服务 *** 作文件,上传下载生成链接删除通知等,第1张

阿里云oss服务 *** 作文件,上传下载生成链接删除通知等

目录

oss关键字解读

pom.xml引入jar包

第1,后台提供上传文件的接口,把文件上传到oss服务器

第2,调用oss服务删除一个文件夹,把文件夹下面的文件都删除

第3,调用oss服务删除一个文件,通过文件名删除

第4,oss生成下载url,通过该url下载文件

第5,oss遍历文件夹下所有文件,然后生成下载url

第6,oss通过生成的url上传文件,上传文件完成后调用callback通知接口

第7,postman测试通过生成的url上传文件


oss关键字解读
# 我的oss服务配置
myAliOss:
  accessKeyId: LTAI5t9NDL66JxRyvy888X4Q
  accessKeySecret: C73sv666EOKXL222kwba7H7CYJvbPq
  # 这个自己登录oss服务找一下,其实也很简单购买的服务器是上海的就是下面的shanghai,北京的就是beijing,其余的都一样
  endpoint: oss-cn-shanghai.aliyuncs.com
  # 文件夹名字,这个自己新建,名称随便写
  bucketName: myImageDir
  # 用于生成的下载链接过期时间,自己也可以在代码写死。单位秒
  expirationSeconds: 600
  # oss通过url上传,生成上传文件的连接,然后通过连接上传文件,上传文件完成后调用callback通知接口
  callbackUrl: http://172.168.1.112:8181/oss/callback
pom.xml引入jar包

  com.aliyun.oss
  aliyun-sdk-oss
  3.13.1



  commons-fileupload
  commons-fileupload
  1.3.1

    
  org.apache.httpcomponents
  httpcore
  4.4.10


  org.apache.httpcomponents
  httpclient
  4.5.6


  org.apache.httpcomponents
  httpmime
  4.3.2


  commons-io
  commons-io
  2.6
  
第1,后台提供上传文件的接口,把文件上传到oss服务器

UploadController.java

import com.bean.ResponseData;
import com.services.AppService;
import com.util.AliyunOSSUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


@Slf4j
@Api(value = "UploadController",tags = {"文件上传"})
@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;


    @ApiOperation(value = "文件上传到阿里OSS存储服务器")
    @PostMapping("/uploadFileOss")
    public ResponseData uploadFileOss(@RequestParam("file") MultipartFile file) {
        try {
            // 上传到OSS
            String uploadUrl = aliyunOSSUtil.upLoad(file);
            return ResponseData.ok(uploadUrl);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseData.fail();
        }
    }

}

AliyunOSSUtil.java

package com.util;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.naturobot.user.config.MyAliMessageConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


@Component
@Slf4j
public class AliyunOSSUtil {


    @Autowired
    private MyAliMessageConfig myAliMessageConfig;

    public String upLoad(MultipartFile file) throws Exception {
        try{
            if (file != null) {
                String filename = file.getOriginalFilename();
                if (!"".equals(filename.trim())) {
                    System.out.println("filename="+filename);
                    String uuidName = UUID.randomUUID().toString().replace("-","")+"_"+filename;
                    File newFile = new File(myAliMessageConfig.getUploadDir()+"/"+uuidName);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();
                    file.transferTo(newFile);
                    // 上传到OSS
                    String fileDownloadUrl = this.upLoadFileToOss(newFile);
                    // 删除文件
                    if(newFile.exists()){
                        newFile.delete();
                    }
                    return fileDownloadUrl;
                }else{
                    log.error("上传的文件名不能为空!");
                    throw new Exception("上传的文件名不能为空!");
                }
            }else{
                log.error("上传的文件为null,请选择一个文件");
                throw new Exception("上传的文件为null,请选择一个文件");
            }
        }catch (Exception e){
            throw e;
        }
    }

    
    private String upLoadFileToOss(File file) throws Exception  {
        log.info("------OSS文件上传开始--------" + file.getName());
        String endpoint = myAliMessageConfig.getOssEndpoint();
        //这里endpoint 在你的bucket列表->点击你的bucket->点击概览中间就有,下面有截图
        System.out.println("获取到的Point为:" + endpoint);
        String accessKeyId = myAliMessageConfig.getAccessKeyId();    //accessKeyId 、accessKeySecret 上面有说到哪里获取
        String accessKeySecret = myAliMessageConfig.getAccessKeySecret();
        String bucketName = myAliMessageConfig.getOssBucketName();  //刚才新建的bucket名称
        String fileHost = myAliMessageConfig.getOssFileHost();   //在刚才新建的bucket下面新建一个目录,这就是那个目录的名称
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String dateStr = format.format(new Date());

        // 判断文件
        if (file == null) {
            return null;
        }
        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            // 判断容器是否存在,不存在就创建
            if (!client.doesBucketExist(bucketName)) {
                client.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                client.createBucket(createBucketRequest);
            }
            // 设置文件路径和名称
            String fileUrl = fileHost + "/" + (dateStr + "/" + file.getName());
            // 上传文件
            PutObjectResult result = client.putObject(new PutObjectRequest(bucketName, fileUrl, file));
            // 设置权限(公开读)
            client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            if (result != null) {
// 这里要注意,shanghai还是不要写死,动态从endpoint中获取,然后拼接
                String fileDownloadUrl = "https://myImageDir.oss-cn-shanghai.aliyuncs.com/" + fileUrl;
                log.info("------OSS文件上传成功------");
                log.info("------download  url=" + fileDownloadUrl);
                log.info("------OSS文件上传成功------");
                return fileDownloadUrl;
            }
        } catch (OSSException oe) {
            log.error(oe.getMessage());
            oe.printStackTrace();
            throw new Exception("OSS服务存储失败!");
        } catch (ClientException ce) {
            log.error(ce.getErrorMessage());
            ce.printStackTrace();
            throw new Exception("阿里OSS服务器连接异常!");
        } finally {
            if (client != null) {
                client.shutdown();
            }
        }
        return null;
    }
}

MyAliMessageConfig.java

package com.config;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.teaopenapi.models.Config;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;


@Configuration
@Slf4j
@Component
@Data
public class MyAliMessageConfig {

    @Value("${myAliOss.accessKeyId}")
    private  String accessKeyId;
    @Value("${myAliOss.accessKeySecret}")
    private  String accessKeySecret;
    @Value("${myUpload.uploadDir}")
    private String uploadDir;
    @Value("${myAliOss.fileHost}")
    private String ossFileHost;
    @Value("${myAliOss.endpoint}")
    private String ossEndpoint;
    @Value("${myAliOss.bucketName}")
    private String logBucketName;
    @Value("${myAliOss.expirationSeconds}")
    private Integer expirationSeconds;
    @Value("${myAliOss.callbackUrl}")
    private String callbackUrl;

  
}

-------------------------------------------------------------------------------------------------------------

第2,调用oss服务删除一个文件夹,把文件夹下面的文件都删除
// oss如果有=userId/20211212
// oss如果有=userId/20211213
// oss如果有=userId/20211214
// oss如果有=userId/20211215
// 如果我要删除userId那么dir=userId/,注意这个斜杠不能少
// 删除逻辑是,把userId文件夹下的所有文件和文件夹都删除,然后把userId这个文件夹也删除
public void deleteOssDir(String dir) {
        OSS ossClient = null;
        try{
            String endpoint = myAliMessageConfig.getOssEndpoint();
            String accessKeyId = myAliMessageConfig.getAccessKeyId();
            String accessKeySecret = myAliMessageConfig.getAccessKeySecret();
            String logBucketName = myAliMessageConfig.getLogBucketName();
            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 删除目录及目录下的所有文件。
            String nextMarker = null;
            ObjectListing objectListing = null;
            do {
                ListObjectsRequest listObjectsRequest = new ListObjectsRequest(logBucketName)
                        .withPrefix(dir)
                        .withMarker(nextMarker);
                objectListing = ossClient.listObjects(listObjectsRequest);
                if (objectListing.getObjectSummaries().size() > 0) {
                    List keys = new ArrayList();
                    for (OSSObjectSummary s : objectListing.getObjectSummaries()) {
                        keys.add(s.getKey());
                        log.info("delete oss applog key={}",s.getKey());
                    }
                    DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(logBucketName).withKeys(keys).withEncodingType(OSSConstants.URL_ENCODING);
                    DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(deleteObjectsRequest);
                }
                nextMarker = objectListing.getNextMarker();
            } while (objectListing.isTruncated());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

-------------------------------------------------------------------------------------------------------------

第3,调用oss服务删除一个文件,通过文件名删除
// fileName=userId/20211213/uuid.png
public void deleteOssZipFile(String fileName) {
        OSS ossClient = null;
        try{
            String endpoint = myAliMessageConfig.getOssEndpoint();
            String accessKeyId = myAliMessageConfig.getAccessKeyId();
            String accessKeySecret = myAliMessageConfig.getAccessKeySecret();
            String logBucketName = myAliMessageConfig.getLogBucketName();
            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            ossClient.deleteObject(logBucketName, fileName);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

 -------------------------------------------------------------------------------------------------------------

第4,oss生成下载url,通过该url下载文件

public String getOssUrl(String fileName) {
        OSS ossClient = null;
        try{
            Date expiration = new Date(System.currentTimeMillis() + (myAliMessageConfig.getExpirationSeconds() * 1000));
            log.info("失效时间="+expiration.toLocaleString());
            String endpoint = myAliMessageConfig.getOssEndpoint();
            log.info("获取到的Point为:" + endpoint);
            String accessKeyId = myAliMessageConfig.getAccessKeyId();
            String accessKeySecret = myAliMessageConfig.getAccessKeySecret();
            String logBucketName = myAliMessageConfig.getLogBucketName();
            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            URL url = ossClient.generatePresignedUrl(logBucketName, fileName, expiration);
            log.info("oss生成的文件下载地址="+url.toString());
            return url.toString();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

 -------------------------------------------------------------------------------------------------------------

第5,oss遍历文件夹下所有文件,然后生成下载url
String dir = vo.getUserId()+"/"+day+"/";
ObjectListing objectListing = ossClient.listObjects(logBucketName,dir);
for (OSSObjectSummary s :  objectListing.getObjectSummaries()) {
  String fileName = s.getKey();
  URL url = ossClient.generatePresignedUrl(logBucketName, fileName, expiration);
  // url就是下载地址,可以list添加url然后返回给前端
}

 -------------------------------------------------------------------------------------------------------------

第6,oss通过生成的url上传文件,上传文件完成后调用callback通知接口
OssClientOssReqVo.java
package com.vo;


import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import javax.validation.constraints.NotNull;
import java.io.Serializable;


@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class OssClientOssReqVo implements Serializable{

    private static final long serialVersionUID = 1L;


    @NotNull(message = "appId不能为空!")
    @ApiModelProperty(value = "应用ID")
    private Long appId;


    @NotNull(message = "taskId不能为空!")
    @ApiModelProperty(value = "任务id")
    private String taskId;


    @NotNull(message = "userId不能为空!")
    @ApiModelProperty(value = "用户ID")
    private Long userId;
}
OssClientOssPolicyResult.java
package com.vo;

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;

@Data
public class OssClientOssPolicyResult implements Serializable {

    @ApiModelProperty("请求方式")
    private String method;

    @ApiModelProperty("oss文件上传的地址")
    private String url;

    @ApiModelProperty("访问身份验证中用到用户标识")
    private String ossAccessKeyId;

    @ApiModelProperty("用户表单上传的策略,经过base64编码过的字符串")
    private String policy;

    @ApiModelProperty("对policy签名后的字符串")
    private String signature;

    @ApiModelProperty("上传文件夹路径前缀")
    private String dir;

    @ApiModelProperty("上传成功后的回调设置")
    private String callback;

    @ApiModelProperty("文件全路径")
    private String key;

    @ApiModelProperty("自己需要上传的文件")
    private String file;

    @ApiModelProperty("生成时间")
    private String createTime;

    @ApiModelProperty("失效时间")
    private String expireTime;

    @ApiModelProperty("Headers中的Content-Type=multipart/form-data; boundary=")
    private String contentType;
}

生成url上传的方法并且带有callback

public OssClientOssPolicyResult create(OssClientOssReqVo vo) {
  OSS ossClient = null;
  OssClientOssPolicyResult result = new OssClientOssPolicyResult();
  try{
      Date now = new Date();
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      // 有效期600秒,修改配置文件
      log.info("调用时间="+now.toLocaleString());
      result.setCreateTime(sdf.format(now));
      Date expiration = new Date(System.currentTimeMillis() + (myAliMessageConfig.getExpirationSeconds() * 1000));
      log.info("失效时间="+expiration.toLocaleString());
      result.setExpireTime(sdf.format(expiration));
      String endpoint = myAliMessageConfig.getOssEndpoint();
      log.info("获取到的Point为:" + endpoint);
      String accessKeyId = myAliMessageConfig.getAccessKeyId();
      String accessKeySecret = myAliMessageConfig.getAccessKeySecret();
      String logBucketName = myAliMessageConfig.getLogBucketName();
      String callbackUrl = myAliMessageConfig.getCallbackUrl();

      // 创建OSSClient实例。
      ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
      // 判断容器是否存在,不存在就创建
      if (!ossClient.doesBucketExist(logBucketName)) {
          ossClient.createBucket(logBucketName);
          CreateBucketRequest createBucketRequest = new CreateBucketRequest(logBucketName);
          createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
          ossClient.createBucket(createBucketRequest);
      }
      Long userId = vo.getUserId();
      String dateStr = vo.getTaskId().substring(0,8);
      String fileName = userId+ MyConstants.PUBLIC_PATH_CHAR_SLASH+vo.getAppId()+MyConstants.PUBLIC_PATH_CHAR_SLASH
              +dateStr+MyConstants.PUBLIC_PATH_CHAR_SLASH+vo.getTaskId()+MyConstants.PUBLIC_FILE_END_WITH_ZIP;

      String dir = userId+ MyConstants.PUBLIC_PATH_CHAR_SLASH+vo.getAppId()+MyConstants.PUBLIC_PATH_CHAR_SLASH
              +dateStr;
      // 单个文件大小限制
      long maxSize = myAliMessageConfig.getMaxSize() * 1024 * 1024;
      // 回调
      OssCallbackParam callback = new OssCallbackParam();
      callback.setCallbackUrl(callbackUrl);
// 下面的参数就是oss服务callback时候回传的参数
      String callbackBody = "{"userId":"+userId+","appId":"+vo.getAppId()+","taskId":""+vo.getTaskId()+""}";
      callback.setCallbackBody(callbackBody);
      callback.setCallbackBodyType("application/json");
      PolicyConditions policyConds = new PolicyConditions();
      policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, maxSize);
      policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, fileName);
      String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
      byte[] binaryData = postPolicy.getBytes(MyConstants.CHAR_SET_UTF8);
      String policy = BinaryUtil.tobase64String(binaryData);
      String signature = ossClient.calculatePostSignature(postPolicy);
      String callbackData = BinaryUtil.tobase64String(JSONUtil.parse(callback).toString().getBytes(MyConstants.CHAR_SET_UTF8));
      // 返回结果
      result.setMethod("post");
      result.setOssAccessKeyId(accessKeyId);
      result.setPolicy(policy);
      result.setSignature(signature);
      result.setDir(dir);
      result.setCallback(callbackData);
      result.setUrl(MyConstants.PUBLIC_PATH_BEGIN_WITH_HTTP + logBucketName + MyConstants.PUBLIC_PATH_CHAR_DOT + endpoint);
      result.setKey(fileName);
      result.setFile("自己需要上传的文件,不管是java还是postman或者其它语言,这个文件属性必须在最后一行加入");
      result.setContentType("multipart/form-data; boundary=");
  } catch (Exception e) {
      e.printStackTrace();
  } finally {
      if (ossClient != null) {
          ossClient.shutdown();
      }
  }
  return result;
}





// OssCallbackParamReqVo.java
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class OssCallbackParamReqVo implements Serializable{

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "用户id")
    private Long userId;

    @ApiModelProperty(value = "应用id")
    private Long appId;

    @ApiModelProperty(value = "taskId")
    private String taskId;

}


// Controller.java
@ApiIgnore("oss回调接口")
@PostMapping("/callback")
public String callback(@RequestBody OssCallbackParamReqVo vo){
    try {
        myService.callback(vo);
        return "success";
    } catch (Exception e) {
        e.printStackTrace();
        return "failure";
    }
}




// Service.java
public void callback(OssCallbackParamReqVo vo)  {
  log.info("回调callback,vo="+vo);
  
  log.info("用户上传文件成功了,快快接收处理吧");
}

 -------------------------------------------------------------------------------------------------------------

第7,postman测试通过生成的url上传文件

 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5686483.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存