原创

vue 阿里云服务端签名直传

温馨提示:
本文最后更新于 2022年10月27日,已超过 918 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

阿里云文档地址https://help.aliyun.com/document_detail/31926.html

1. java服务器签名接口


    /**1.来源阿里云文档https://help.aliyun.com/document_detail/91868.htm?spm=a2c4g.11186623.0.0.160729ecESp4lQ#concept-ahk-rfz-2fb
    *  2.采用简单上传方式,删除了回调相关的参数
    *  3.此处可以根据需求,将OSSClient封装成一个单例,这样每次在获取签名时不用重新生成对象    
    **/
    @GetMapping("/oss/policy")
    public ResponseResult getPolicy() {
        String accessId = "请填写您的AccessKeyId。"; // 请填写您的AccessKeyId。
        String accessKey = "请填写您的AccessKeySecret"; // 请填写您的AccessKeySecret。
        String endpoint = "oss-cn-hangzhou.aliyuncs.com"; // 请填写您的 endpoint。
        String bucket = "请填写您的 bucketname"; // 请填写您的 bucketname 。
        String host = "http://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint
        String dir = "bucket中文件夹名称/"; // 用户上传文件时指定的前缀。(上传到哪个文件夹)

        OSSClient client = new OSSClient(endpoint, accessId, accessKey);
        Map<String, String> respMap = new LinkedHashMap<String, String>();
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

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

            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        //ResponseResult是自己服务的包装方法,改成自己的即可
        return ResponseResult.success(respMap);
    }

2. vue上传

        //上传组件  来自 element ==》 upload
        <el-upload
            drag
            class="avatar-uploader"
            :data = signParam //从后台获取的签名对象
            action="https://bucket名称.oss-cn-hangzhou.aliyuncs.com" //阿里云上传的路径 bucket名称+服务器名
            :on-success="handleAvatarSuccess" //上传成功调用
            :before-upload="beforeAvatarUpload"    //上传前调用
            >
          </el-upload>
        //上传前调用
        beforeAvatarUpload(file){
            let _self = this
            //给文件名加uuid
            this.uuid = uuid.v1()
            //等待执行完后再返回
            return new Promise((resolve, reject) => {
              //从后台获取签名的接口  
              userApi.policy().then((response) => {
                _self.signParam.policy = response.data.policy;
                _self.signParam.signature = response.data.signature;
                _self.signParam.ossaccessKeyId = response.data.accessid;
                _self.signParam.key = response.data.dir +this.uuid+"_"+'${filename}';
                _self.signParam.dir = response.data.dir;
                _self.signParam.host = response.data.host;
                resolve(true)
              });
            })
        }
//userApi
import request from '@/utils/request'
export default {
  //获取上传签名
  policy(){
    return request({
      url: '/oss/policy',
      method: 'get'
    })
  }
}
npm install vue-uuid  //安装uuid
import { uuid } from 'vue-uuid'; //在局部文件使用

3.获取图片宽高

    //url是能访问到的图片路径
    getImageSize(url) {
          return new Promise((resolve) => {
              var img = document.createElement("img");
              img.src = url;
              img.onload = () => {
              // 为什么要写 onload  是因为要等他加载完之后才能获取到图片宽高
                  resolve({width:img.naturalWidth,height: img.naturalHeight});
              };
          });
    }
正文到此结束