使用浏览器上的javascript在Google API上发送发布请求 [英] Send post request on Google API using javascript on browser

查看:132
本文介绍了使用浏览器上的javascript在Google API上发送发布请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Google API中的$ .ajax请求中遇到404错误. 我有这些代码,

I am getting 404 error on my $.ajax request in Google API. I have these codes,

var asyncLoad = require('react-async-loader');
var CLIENT_ID = '<SOME_ID>';
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/drive/v3/rest"];
  var SCOPES = 'https://www.googleapis.com/auth/drive';

const mapScriptToProps = state => ({
   gapi: {
     globalPath: 'gapi',
     url: 'https://apis.google.com/js/api.js'
   }
});

@asyncLoad(mapScriptToProps)
...

我使用react的异步加载程序在bundle.js之前获取Google API. 然后,我得到属性中的gapi.这是我提交表单的下一个代码.

I used async loader of react to get the Google API before the bundle.js. Then I get the gapi in the properties. Here is my next codes for submitting a form.

submitForm(e){
e.preventDefault();
var data = this.refs.file.files[0];
var self = this;
var formData = new FormData();
formData.append('data', data); 
$.ajax({
    url: "https://www.googleapis.com/upload/drive/v3?uploadType=media&access_token="+encodeURIComponent(self.state.token),
    type: "POST",
    processData: false,
    data: formData,
    beforeSend: function (xhr) {
      /* Authorization header */
      xhr.setRequestHeader("Authorization", "Bearer " + self.state.token);
      xhr.setRequestHeader('X-Upload-Content-Length', data.size);
      xhr.setRequestHeader("Content-Type", "image/jpeg");
      xhr.setRequestHeader('X-Upload-Content-Type', "image/jpeg");
  },
    success: function(data){
        if(typeof data === "string") data = JSON.parse(data);
        console.log(data);
        if(data.success){
            console.log("done");
        }else {
            console.log("error");
        }
    }
});

}

因此,在这里,当单击按钮上传时,我将调用SubmitForm函数.我也用ref="file"输入文件.这是在客户端(浏览器)端运行的.我收到404错误.

So here, I call submitForm function when the button upload is clicked. I have also file input with ref="file". This is run in client (browser) side. I got 404 error.

我在这里要做的是将图像文件上传到Google驱动器.我该怎么做呢?我的问题有解决办法吗?

What I am trying to do here is to upload an image file to google drive. How can I do this right? Any solution for my problem?

推荐答案

由于url缺少files部分:https://www.googleapis.com/upload/drive/v3/files?uploadType=media,因此导致404错误.请参见 Google云端硬盘API> REST-文件:创建.

The 404 error is caused because the url is missing the files part: https://www.googleapis.com/upload/drive/v3/files?uploadType=media. See Google Drive APIs > REST - Files: create.

我设法通过FileReader.readAsDataURL()方法上传了从<input type="file" accept="image/*">读取的图像,如下所示:

I managed to upload an image that was read from <input type="file" accept="image/*"> with FileReader.readAsDataURL() method as follows:

var metadata = {
    name: 'image.jpg',
    mimeType: 'image/jpeg'
}

var user = gapi.auth2.getAuthInstance().currentUser.get();
var oauthToken = user.getAuthResponse(true).access_token;

var boundary = 'foo_bar_baz';
var data = '--' + boundary + '\n';
data += 'content-type: application/json; charset=UTF-8' + '\n\n';
data += JSON.stringify(metadata) + '\n';
data += '--' + boundary + '\n';

var dataURL = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAZABkAAD/7AARRHVja3kAAQAEAAAAZAAA/+EKhWh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8APD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZ...'
var dataURLparts = dataURL.split(',', 2);
var dataURLheaderParts = dataURLparts[0].split(':');
var dataURLheaderPayloadParts = dataURLheaderParts[1].split(';');

data += 'content-transfer-encoding: ' + dataURLheaderPayloadParts[1] + '\n';
data += 'content-type: ' + dataURLheaderPayloadParts[0] + '\n\n';
data += dataURLparts[1] + '\n';
data += '--' + boundary + '--';

$.ajax({
    type: 'POST',
    url: 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart',
    beforeSend: function (xhr) {
        xhr.setRequestHeader("Authorization", "Bearer " + oauthToken);
     },
     contentType: 'multipart/related; boundary=' + boundary,
     data: data,
     processData: false
 }).done(function(response) {
     console.log(response);
 });

这篇关于使用浏览器上的javascript在Google API上发送发布请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆