使用javascript的json api上传到谷歌云商店

Vik*_*Vik 7 javascript client-library google-cloud-storage json-api gapi

我试图使用gapi上传图片到谷歌云存储.目前的代码,我是

<script src="https://apis.google.com/js/api.js"></script>
<script type="text/javascript">
var imgData = null;

function getImage() {
    navigator.camera.getPicture(onSuccess, onFailure, {
        destinationType: navigator.camera.DestinationType.FILE_URI,
        sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
    });

    function onSuccess(imageURI) {
        imgData = encodeImageUri(imageURI);
        var contentLen = imgData.length;
        gapi.load('client', start);
    }

    function onFailure(message) {
        alert("Get image failed: " + message);
    }
}

function start() {
    // 2. Initialize the JavaScript client library.
    console.log('firing google storage api');
    gapi.client.init({
        'apiKey': 'XXX-XX'
    }).then(function() {
        // 3. Initialize and make the API request.
        console.log('api initialized');
        var request = gapi.client.request({
            'path': 'https://www.googleapis.com/upload/storage/v1/b/visionapibucket/o?uploadType=media&name=myObject',
            'method': 'POST',
            'headers': {
                'Content-Type': 'image/jpeg'
            },
            'body': imgData
        });

        try {
            //Execute the insert object request
            console.log('executing call');
            request.execute(function(resp) {
                alert(resp);
            });

        } catch (e) {
            console.log('An error has occurred: ' + e.message);
        }
    }).then(function(response) {
        console.log(response.result);
    }, function(reason) {
        console.log('Error: ' + reason.result.error.message);
    });
};
</script>
Run Code Online (Sandbox Code Playgroud)

我可以看到代码在控制台中的命令是:api initialized

但我没有看到gapi.client.request调用甚至打印任何错误等.

我不确定这里有什么问题.请指教

Ami*_*ein 1

您无法仅使用 API 密钥将文件上传到 Google 存储。您必须有一个 oauth 令牌。

\n
\n

如果请求需要授权(例如请求个人的私有数据),则应用程序必须随请求提供 OAuth 2.0 令牌。应用程序还可以提供 API 密钥,但这不是必须的。

\n

如果请求不需要授权(例如对公共数据的请求),则应用程序必须提供 API 密钥或 OAuth 2.0 令牌,或者两者都提供\xe2\x80\x94任何对您来说最方便的选项。

\n
\n

https://cloud.google.com/storage/docs/json_api/v1/how-tos/authorizing

\n

就您而言,您想要上传,因此您必须拥有 oauth 令牌。

\n

您有几种解决方法:

\n\n

有关实用程序的更多信息gcloud以及下载:https: //cloud.google.com/sdk/

\n