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被调用甚至打印任何错误等.
我不确定这里有什么问题.请指教
您无法仅使用 API 密钥将文件上传到 Google 存储。您必须有一个 oauth 令牌。
\n\n\n如果请求需要授权(例如请求个人的私有数据),则应用程序必须随请求提供 OAuth 2.0 令牌。应用程序还可以提供 API 密钥,但这不是必须的。
\n如果请求不需要授权(例如对公共数据的请求),则应用程序必须提供 API 密钥或 OAuth 2.0 令牌,或者两者都提供\xe2\x80\x94任何对您来说最方便的选项。
\n
https://cloud.google.com/storage/docs/json_api/v1/how-tos/authorizing
\n就您而言,您想要上传,因此您必须拥有 oauth 令牌。
\n您有几种解决方法:
\n您可以将文件上传到您的服务器,并使用服务帐户使用您的服务器凭据上传该文件。
\n https://cloud.google.com/compute/docs/access/service-accounts
您可以在服务器上创建一个令牌,并将其发送到您的客户端。然后,客户端可以将一个文件上传到您的 Google 存储帐户,而无需永久访问令牌
\n您可以上传到您用户的 Google 存储帐户。为此,他们必须登录您的应用。\n https://developers.google.com/identity/protocols/OAuth2
\n最后一种方法是,您可以将文件上传到您的服务器,然后通过执行gutil mv命令将其复制到云端。在这种情况下,您所要做的就是使用 gcloud auth\n gustil mv ,\n gcloud mv 命令登录一次您的 Google 云帐户
有关实用程序的更多信息gcloud以及下载:https: //cloud.google.com/sdk/
| 归档时间: |
|
| 查看次数: |
896 次 |
| 最近记录: |