使用Javascript

时间:2016-04-17 22:09:14

标签: javascript google-drive-api

我正在尝试将输入Textarea的文本上传到Google云端硬盘文件(mimetype:text / x-java for java源代码。)

我尝试合并Drive Rest Files API中提到的更新和插入方法,但仍然遇到401错误。可以在https://jgloud.net找到该实施。

任何帮助都将不胜感激。

  // save content to google drive
  function updateOrInsert(fileId, folderId, text, callback) 
  {
    const boundary = '-------314159265358979323846';
    const delimiter = "\r\n--" + boundary + "\r\n";
    const close_delim = "\r\n--" + boundary + "--";
    checkAuth();
    var contentType = "text/x-java";
    var myToken = accesstoken || gapi.auth.getToken();

    // if fileId exists, the file exists, use update method

    if (fileId) 
    {
      var metadata = {'mimeType': contentType,};

      var multipartRequestBody =
          delimiter +  'Content-Type: application/json\r\n\r\n' +
          JSON.stringify(metadata) +
          delimiter + 'Content-Type: ' + contentType + '\r\n' + '\r\n' +
          text +
          close_delim;

      if (!callback) { callback = function(file) { console.log("Update Complete ",file) }; }

      gapi.client.request({ 
          'path': '/upload/drive/v2/files/'+folderId+"?fileId="+fileId+"&uploadType=multipart",
          'method': 'PUT',
          'params': {'fileId': fileId, 'uploadType': 'multipart'},
          'headers': { 'Authorization': 'Bearer '+myToken.access_token,
                       'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'},
          'body': multipartRequestBody,
      });
    }
    else
    {
      //no file present, must create a new one.  use insert method

      var reader = new FileReader(); 
      var fileData = new Blob([text], {type:'text/x-java'});
      reader.readAsBinaryString(fileData);
      reader.onload = function(e) {
      var contentType = fileData.type || 'text/x-java';
      var metadata = {
                       'title': filename,
                       '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/drive/v2/files',
            'method': 'POST',
            'params': {'uploadType': 'multipart'},
            'headers': {
                         'Authorization': 'Bearer '+myToken.access_token,
                         'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
                       },
            'body': multipartRequestBody
          }                             );
      if (!callback) 
      {
        callback = function(file) { console.log(file) };
      }
      request.execute(callback);
    }
  }
}

2 个答案:

答案 0 :(得分:1)

尝试退房并尝试使用quickstart获取javascript。

<html>
  <head>
    <script type="text/javascript">
      // Your Client ID can be retrieved from your project in the Google
      // Developer Console, https://console.developers.google.com
      var CLIENT_ID = '<YOUR_CLIENT_ID>';

      var SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'];

      /**
       * Check if current user has authorized this application.
       */
      function checkAuth() {
        gapi.auth.authorize(
          {
            'client_id': CLIENT_ID,
            'scope': SCOPES.join(' '),
            'immediate': true
          }, handleAuthResult);
      }

      /**
       * Handle response from authorization server.
       *
       * @param {Object} authResult Authorization result.
       */
      function handleAuthResult(authResult) {
        var authorizeDiv = document.getElementById('authorize-div');
        if (authResult && !authResult.error) {
          // Hide auth UI, then load client library.
          authorizeDiv.style.display = 'none';
          loadDriveApi();
        } else {
          // Show auth UI, allowing the user to initiate authorization by
          // clicking authorize button.
          authorizeDiv.style.display = 'inline';
        }
      }

      /**
       * Initiate auth flow in response to user clicking authorize button.
       *
       * @param {Event} event Button click event.
       */
      function handleAuthClick(event) {
        gapi.auth.authorize(
          {client_id: CLIENT_ID, scope: SCOPES, immediate: false},
          handleAuthResult);
        return false;
      }

      /**
       * Load Drive API client library.
       */
      function loadDriveApi() {
        gapi.client.load('drive', 'v3', listFiles);
      }

      /**
       * Print files.
       */
      function listFiles() {
        var request = gapi.client.drive.files.list({
            'pageSize': 10,
            'fields': "nextPageToken, files(id, name)"
          });

          request.execute(function(resp) {
            appendPre('Files:');
            var files = resp.files;
            if (files && files.length > 0) {
              for (var i = 0; i < files.length; i++) {
                var file = files[i];
                appendPre(file.name + ' (' + file.id + ')');
              }
            } else {
              appendPre('No files found.');
            }
          });
      }

      /**
       * Append a pre element to the body containing the given message
       * as its text node.
       *
       * @param {string} message Text to be placed in pre element.
       */
      function appendPre(message) {
        var pre = document.getElementById('output');
        var textContent = document.createTextNode(message + '\n');
        pre.appendChild(textContent);
      }

    </script>
    <script src="https://apis.google.com/js/client.js?onload=checkAuth">
    </script>
  </head>
  <body>
    <div id="authorize-div" style="display: none">
      <span>Authorize access to Drive API</span>
      <!--Button for the user to click to initiate auth sequence -->
      <button id="authorize-button" onclick="handleAuthClick(event)">
        Authorize
      </button>
    </div>
    <pre id="output"></pre>
  </body>
</html>

使用Drive API时,这将有助于您熟悉代码和一些必需的步骤。希望它有所帮助。

答案 1 :(得分:0)

我看了一下网络标签,试图将文档保存到谷歌,看起来它返回了身份验证错误,你看过他们的客户端身份验证文档了吗? https://developers.google.com/drive/v2/web/auth/web-client#handling_authorization_requests

这是错误,

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Login Required",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Login Required"
 }
}