阿里云oss文件服务器

目录

      • 1.后台提供OSS签名API
        • 1.1.OSS参数配置
        • 1.2.签名接口
      • 2.后台提供OSS签名API
        • 2.1.上传组件
        • 2.2. JS获取签名

1.后台提供OSS签名API

1.1.OSS参数配置

file:
  alicloud:
    bucket-name: itsource-hrm #上传空间bucket
    access-key: LTAI4GBU4kV67teSKSzkKpxN #你的key
    secret-key: 0f9Djm2Ypds2mMBOma7iuInLqlbJL9 #你的秘钥
    endpoint: oss-cn-chengdu.aliyuncs.com  #上传端点
    

1.2.签名接口

@RestController
public class AlicloudOSSController {

    @Autowired
    private AlicloudOSSProperties properties;

    @GetMapping("/oss/sign")
    public AjaxResult ossSign(){
        // host的格式为 bucketname.endpoint
        String host = "https://" + properties.getBucketName() + "." + properties.getEndpoint();

        // 用户上传文件时指定的前缀。
        String dir = "itsource";
        // 创建OSSClient实例。
        OSS ossClient = null;
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);

            // PostObject请求最大可支持的文件大小为5 GB,即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(properties.getEndpoint(), properties.getAccessKey(), properties.getSecretKey());

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            Map<String, String> respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", properties.getAccessKey());
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));

            return AjaxResult.me().setResultObj(respMap);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        } finally {
            if(ossClient != null){
                ossClient.shutdown();
            }
        }
        return null;
    }
}

2.后台提供OSS签名API

2.1.上传组件

<el-upload
        class="upload-demo"
        action="http://itsource-hrm.oss-cn-chengdu.aliyuncs.com"
        :data="uploadData"
        :before-upload="beforeUpload"
        :on-success="handleSuccess"
        :file-list="fileList"
        list-type="picture">
  <el-button size="small" type="primary">点击上传el-button>
  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kbdiv>
el-upload>

2.2. JS获取签名

export default {
    data() {
        return {
            uploadData: {  //提交到OSS的参数
              policy: '',
              signature: '',
              key: '',
              ossaccessKeyId: '',
              dir: '',
              host: ''
            }
        };
    },
    methods: {
      getUUID() {
        var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
          s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "-";
        var uuid = s.join("");
        return uuid;
      },
      async beforeUpload(){
        await this.$http.get("/file/oss/sign").then(response=>{
                //设置相关的参数
              var resultObj = response.data.resultObj;
              alert(this.uploadData.policy);
              this.uploadData.policy = resultObj.policy;
              alert(this.uploadData.policy);

              this.uploadData.signature = resultObj.signature;
              this.uploadData.ossaccessKeyId = resultObj.accessid;
                  //上传的文件名,使用UUID处理一下
              this.uploadData.key = resultObj.dir + '/'+this.getUUID()+'_${filename}';
              this.uploadData.dir = resultObj.dir;
              this.uploadData.host = resultObj.host;
           });
      },
      handleSuccess(res, file) {
        this.fileList.pop();
        //上传的完整的文件地址
        var urlPath = this.uploadData.host + '/' + this.uploadData.key.replace("${filename}",file.name) ;
        this.employee.logo = urlPath;
        this.$message({message: '上传成功,图片地址:'+this.employee.logo, type: 'success' });
      },
      handleRemove(file, fileList) {
        
      },
      handlePreview(file) {
        
      }
}

你可能感兴趣的:(文档,java,阿里云)