【发布时间】:2017-05-21 20:06:16
【问题描述】:
我正在尝试使用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>
我可以看到代码正在命中
控制台中的语句是:api initialized
但我没有看到gapi.client.request 被调用,甚至没有打印任何错误等。
我不确定这里出了什么问题。请指教
【问题讨论】:
-
我对此
google api了解不多,但我可以告诉你一件事,gapi.client.request的参数 是path,method,params,header,body记录在here,请在更正后发送您的输入。 -
只是路径是必需的,其他都是可选的
-
但
content type不是参数,应该发送为header {'Content-type' : 'image/jpeg'},请在更正后发送您的输入 -
没有帮助。在问题中更新了我的代码
-
你能不能把
gapi.client.request移动到try,看看这个语句是否抛出异常。另外,这个网站 (googleapis.com) 在你身边吗?
标签: javascript google-cloud-storage json-api google-api-js-client client-library