SpringBoot+Vue实现阿里云oss服务端签名直传并设置上传回调

demo地址:
链接: aliyun_oss_upload.
1.upload.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <!-- import CSS -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</head>
<style>
    .screenshot{
        margin-top: 80px;
        position: relative;
    }
</style>
<body>
<div id="app">
    <div>选择图片:<input type="file" ref="file"></div>
    <el-button type="primary" @click="getPolicy">上传</el-button>
    <!--图片部分-->
    <div id="screenshot" class="screenshot">
        <span v-for="(imgUrl, index) in srcList" :key="index" class="slideshow">
          <el-image style="width:175px; height: 116px"
                    :src="imgUrl"
                    :preview-src-list="srcList"
          />
        </span>
    </div>
</div>
</body>
<!-- import Vue before Element -->
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<!-- import JavaScript -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
    new Vue({
        el: '#app',
        data: function() {
            return {
                dialogImageUrl: '',
                dialogVisible: false,
                srcList: []
            };
        },
        methods: {
            handleRemove(file, fileList) {
                console.log(file, fileList);
            },
            getPolicy(){
                const that = this;
                // 获取阿里云上传签名
                axios.get('http://localhost:8080/aliyun/oss/policy')
                    .then(function (response) {
                     that.ossUpload(that.$refs.file.files[0],response.data.resultContent);
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            ossUpload(file,ossToken){
                const filename =file.name;
                let formData = new FormData();
                //注意formData里append添加的键的大小写
                console.log(ossToken)
                formData.append('key', ossToken.dir + filename); //存储在oss的文件路径
                formData.append('OSSAccessKeyId', ossToken.accessid); //accessKeyId
                formData.append('policy', ossToken.policy); //policy
                formData.append('Signature', ossToken.signature); //签名
                formData.append('callback', ossToken.callback); //回调
                formData.append('success_action_status', 200); //成功后返回的操作码
                //如果是base64文件,那么直接把base64字符串转成blob对象进行上传就可以了
                formData.append("file",file);
                axios.post(ossToken.host,formData,{
                    'Content-Type':'multipart/form-data'
                }).then(res=>{
                   console.log(res)
                    this.srcList.push(res.data.resultContent.filename);
                })

            }
        }
    })
</script>
</html>

2.签名生成

   public ResultBean getPolicy() {
        JSONObject resultBean = new JSONObject();
        // 存储目录
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dir = ALIYUN_OSS_DIR_PREFIX+sdf.format(new Date())+"/";
        // 签名有效期
        long expireEndTime = System.currentTimeMillis() + ALIYUN_OSS_EXPIRE * 1000;
        Date expiration = new Date(expireEndTime);
        // 文件大小
        long maxSize = ALIYUN_OSS_MAX_SIZE * 1024 * 1024;
        // 回调
        OssCallbackParam callback = new OssCallbackParam();
        callback.setCallbackUrl(ALIYUN_OSS_CALLBACK);
        callback.setCallbackBody("filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
        callback.setCallbackBodyType("application/x-www-form-urlencoded");
        // 提交节点
        String action = "https://" + ALIYUN_OSS_ENDPOINT;
        try {
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, maxSize);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String policy = BinaryUtil.toBase64String(binaryData);
            String signature = ossClient.calculatePostSignature(postPolicy);
            String callbackData = BinaryUtil.toBase64String(JSONUtil.parse(callback).toString().getBytes("utf-8"));
            resultBean.put("accessid",ossClient.getCredentialsProvider().getCredentials().getAccessKeyId());
            resultBean.put("policy",policy);
            resultBean.put("signature",signature);
            resultBean.put("dir",dir);
            resultBean.put("expire",String.valueOf(expireEndTime / 1000));
            resultBean.put("callback",callbackData);
            resultBean.put("host",action);
            // 返回结果
        } catch (Exception e) {
            LOGGER.error("签名生成失败", e);
            return new ResultBean(Constants.RESCODE_SIGNATION_FAILED,Constants.RESMSG_SIGNATION_FAILED);
        }
        return new ResultBean(Constants.RESCODE_SUCCESS,Constants.RESMSG_SUCCESS,resultBean);
    }
    ```
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值