【问题标题】:Google Cloud Storage Upload unauthorized谷歌云存储上传未经授权
【发布时间】:2017-02-01 01:11:03
【问题描述】:

我想使用 javascript 将文件上传到谷歌云存储,我正在使用 google api javascript。

我的存储桶不是公开的,我需要配置写入权限,但云存储需要身份验证。

我尝试了很多类型的配置,但我对 GAE 身份验证知之甚少。

所以,当我尝试发送文件时,显示以下消息:

“message”:“匿名用户没有 storage.objects.create 对存储桶 boti-lab-dev 的访问权限。”

按照我的代码:

function start() {
  // 2. Initialize the JavaScript client library.
  gapi.client.init({
    'apiKey': 'myApiKey',
    // clientId and scope are optional if auth is not required.
    'clientId': 'xxxbug.apps.googleusercontent.com',
    'scope': 'https://www.googleapis.com/auth/devstorage.read_write',

  }).then(function() {
    // 3. Initialize and make the API request.
    return gapi.client.request({
      'method': 'post',
      'path': 'https://www.googleapis.com/upload/storage/v1/b/myBucket/o?uploadType=media&name=nameOfFile',
        'header': {
          'Authorization': 'Bearer ya29.mykey'
        }
    })
  }).then(function(response) {
    console.log(response.result);
  }, function(reason) {
    console.log('Error: ' + reason.result.error.message);
  });
};
// 1. Load the JavaScript client library.
gapi.load('client', start);

我需要创建或配置什么? 谢谢

【问题讨论】:

    标签: google-cloud-storage google-cloud-endpoints


    【解决方案1】:

    以下对我来说就像一个魅力:

    1/ 添加以下javascript:

    function init() {
        gapi.client.setApiKey(yourApiKey);
        window.setTimeout(checkAuth, 1);
    }
    
    function checkAuth() {
        gapi.auth.authorize({
            client_id: yourClientId,
            scope: yourApiScopes,
            immediate: true
        }, handleAuthResult);
    }
    
    function handleAuthResult(authResult) {
        if (authResult && !authResult.error) {
             //do something
        } else {
    
            $("#loginButton").click(function () {
                handleAuthClick();
            });
    
        }
    }
    
    function handleAuthClick() {
        gapi.auth.authorize({
            client_id: yourClientId,
            scope: yourApiScopes,
            immediate: false
        }, handleAuthResult);
        return false;
    }
    

    yourApiScopes 等于

    "email https://www.googleapis.com/auth/devstorage.read_write"
    

    2/ 在 HTML 页面的末尾添加这一行

    <script src="https://apis.google.com/js/client.js?onload=init"></script>
    

    3/ 上传文件,功能如下:

    function uploadFile(fileData, bucket) {
        var boundary = '-------314159265358979323846';
        var delimiter = "\r\n--" + boundary + "\r\n";
        var close_delim = "\r\n--" + boundary + "--";
        var reader = new FileReader();
        reader.readAsBinaryString(fileData);
    
        reader.onload = function (e) {
            var contentType = fileData.type || 'application/octet-stream';
            var metadata = {
                'name': fileData.name,
                'mimeType': contentType
            };
            var base64Data = btoa(reader.result);
            var multipartRequestBody =
                    delimiter +
                    'Content-Type: application/json\r\n\r\n' +
                    JSON.stringify(metadata) +
                    delimiter +
                    'Content-Type: ' + contentType + '\r\n' +
                    'Content-Transfer-Encoding: base64\r\n' +
                    '\r\n' +
                    base64Data +
                    close_delim;
    
            var request = gapi.client.request({
                'path': '/upload/storage/v1/b/' + bucket + '/o',
                'method': 'POST',
                'params': {'uploadType': 'multipart'},
                'headers': {
                    'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
                },
                'body': multipartRequestBody
            });
    
            try {
                request.execute(function (resp) {
                    if (resp.hasOwnProperty("error")) {
                        //do something for error
                    } else {
                       //do something for success
                        }
                    }
                });
            }
            catch (e) {
               //do something
            }
    
        };
    
    }
    

    【讨论】:

      【解决方案2】:

      我明白了。 我使用了下面的代码:

      它对我有用,我知道它不好,因为我正在发送一个 Token Bearer。 我测试了您的解决方案并且也有效,谢谢。 您的解决方案更好,因为您使用的是 api google。

      function sentStorage(token, bucket, x-goog-project-id) {
             var file =  document.getElementById("myFile").files[0];
             var url = 'https://www.googleapis.com/upload/storage/v1/b/'
             url += bucket + o?uploadType=media&name=' + file;
             xhr = new XMLHttpRequest();
      
             xhr.open('POST', url);
             xhr.setRequestHeader('Content-Type', file.type);
      
             xhr.setRequestHeader('x-goog-project-id', x-goog-project-id);
             xhr.setRequestHeader('Authorization', 'Bearer ' + token);
      
             xhr.send(file);
      
             xhr.onreadystatechange = function () {
                 if (xhr.readyState === 4) {
                     var response = JSON.parse(xhr.responseText);
                     if (xhr.status === 200) {
                         alert('codigo 200');
                     } else {
                       var message = 'Error: ' + response.error.message;
                       console.log(message);
                         alert(message);
      
                     }
                 }
             };
         }
      

      【讨论】:

        猜你喜欢
        • 2022-01-18
        • 1970-01-01
        • 2015-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-30
        • 1970-01-01
        相关资源
        最近更新 更多