Vue使用axios服务端签名,前端直传阿里Oss

前端html

<input type="file" ref="fileId" @change="getFile">

前端上传函数

getFile: function () {
      this.$axios.get('自己的服务端签名url', {
        params: {},
        headers: {}
      }).then((res) => {
        console.log(res.data.result)
        const params = res.data.result
        const request = new FormData()
        const file = this.$refs.fileId.files[0]
        request.append('key', params.dir + params.fileName + '.xls')
        request.append('policy', params.policy)
        request.append('OSSAccessKeyId', params.accessId)
        request.append('success_action_status', '200')
        request.append('Signature', params.signature)
        request.append('name', params.fileName + '.txt')
        request.append('file', file.file)
        this.$axios({
          url: params.host,
          method: 'post',
          data: request,
          headers: { 'Content-Type': 'multipart/form-data' }
        }).then((res) => {

        })
      })
    }

后端签名代码

    private Map<String, String> getSignature(String host,String dirPrefix) {

        Long userId = UserContext.getUser().getId();
        String prefix =  dirPrefix + userId + "/";
        String fileName = UUID.randomUUID().toString();

        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 10000;
            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, prefix);

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

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

            return respMap;
        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
        }
        return null;
    }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值