美文网首页
阿里云 OSS PostObject上传 服务端签名 回调

阿里云 OSS PostObject上传 服务端签名 回调

作者: 张建勇9511 | 来源:发表于2020-07-09 10:02 被阅读0次

    1.服务端代码

    public RestResponse aliossUploadUrlCallback(AliOssUploadUrlReqForm reqForm) throws ModelChangeException, UnsupportedEncodingException {
    
            FileUploadInfo info = new FileUploadInfo();
    
            String dir = reqForm.getUserId() + "/";
            String fileName = uuidName(reqForm.getFileName());
            String key = dir + fileName;
            String host = ossEndpoint.replace("https://", "https://" + bucket + "."); // 提交表单的URL为bucket域名
    
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(ossEndpoint, ossAccessId, ossAccessKey);
            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);
    
                String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
                byte[] binaryData = postPolicy.getBytes("utf-8");
                String encodedPolicy = BinaryUtil.toBase64String(binaryData);
                String postSignature = ossClient.calculatePostSignature(postPolicy);
    
                /*callback*/
                JSONObject jasonCallback = new JSONObject();
                /*配置回调地址*/
                jasonCallback.put("callbackUrl", callbackUrl);
                jasonCallback.put("callbackBody",
          "key=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
                jasonCallback.put("callbackBodyType", "application/x-www-form-urlencoded");
                String base64CallbackBody = BinaryUtil.toBase64String(jasonCallback.toString().getBytes());
    
                info.setOSSAccessKeyId(ossAccessId);
                info.setDir(dir);
                info.setPolicy(encodedPolicy);
                info.setSignature(postSignature);
                info.setKey(key);
    
                info.setHost(host);
                info.setExpire(expireEndTime);
                info.setCallback(base64CallbackBody);
    
                File file = fileFactory.create(key, bucket, ossEndpoint);
                fileService.save(file);
    
                info.setFile(file.model());
    
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return RestResponse.failure(ResCodeMsg.RES_EXCEPTION_SYSTEM)
                        .setAny(RESPONSE_KEY_ERROR, e.getMessage());
            } finally {
                ossClient.shutdown();
            }
    
            return RestResponse.success().setAny(RESPONSE_KEY_FILE_UPLOAD_INFO, info);
        }
    

    2.前端vue实现代码

    <template>
        <div>
            <p>{{uploadInfo}}</p>
            <input type="file" @change="upload($event)">
        </div>
    </template>
    
    <script>
        export default {
            name: "FileUpload",
            data() {
                return {
                    uploadInfo: ''
                }
            }, mounted: async function () {
              /*获取上传oss需要用到的表单信息*/
                await this.axios.post("http://****/aliossUploadUrlCallback").then(res => {
                    console.log(res.data.file)
                    this.uploadInfo = res.data.file
                })
            }, methods: {
                upload(e) {
                    console.log(e.target.files[0])
                    const file = e.target.files[0]
                    const header = {
                        headers: {
                            'Content-Type': 'multipart/form-data;',
                        }
                    }
                    console.log(this.uploadInfo)
                    let formData = new FormData
                    formData.append("key", this.uploadInfo.key)
                    formData.append("name", file.name)
                    formData.append("OSSAccessKeyId", this.uploadInfo.OSSAccessKeyId)
                    formData.append("policy", this.uploadInfo.policy)
                    formData.append("signature", this.uploadInfo.signature)
    
                    //formData.append("expire",this.uploadInfo.expire)
                    formData.append("callback", this.uploadInfo.callback)
    
                    formData.append("file", file)
     
                  /*上传OSS*/
                    this.axios.post(this.uploadInfo.host, formData, header).then(res => {
                        console.log(res)
                    })
                }
            }
        }
    </script>
    
    <style scoped>
    
    </style>
    
    

    3.回调

    前端上传完图片,后台回调地址就会收到oss的回调

    注意:上传OSS时文件要放在表单的最后一个域,key要放在表单的第一个域

    image.png

    相关文章

      网友评论

          本文标题:阿里云 OSS PostObject上传 服务端签名 回调

          本文链接:https://www.haomeiwen.com/subject/vtljcktx.html