使用Javascript将文本从Textarea保存到Google Drive [英] Save Text from Textarea to Google Drive using Javascript

查看:107
本文介绍了使用Javascript将文本从Textarea保存到Google Drive的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将输入到Textarea的文本上传到Google Drive文件(对于java源代码,mimetype:text / x-java。)

我试图合并 Drive Rest Files API 中提到的更新和插入方法,但不断收到401错误。该实现可以在 https://jgloud.net 找到。



任何帮助将不胜感激。

  //将内容保存到谷歌驱动
函数updateOrInsert(fileId,folderId,文本,回调)
{
const boundary ='------- 314159265358979323846';
const delimiter =\r\\\
--+ boundary +\r\\\
;
const close_delim =\r\\\
--+ boundary + - ;
checkAuth();
var contentType =text / x-java;
var myToken = accesstoken || gapi.auth.getToken();

//如果fileId存在,文件存在,使用update方法

if(fileId)
{
var metadata = {'mimeType':内容类型,};

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

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

gapi.client.request({$ b $'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
{
//没有文件存在,必须创建一个新文件。使用插入方法

var reader = new FileReader();
var fileData = new Blob([text],{type:'text / x-java'});
reader.readAsBinaryString(fileData);
reader.onload = function(e){
var contentType = fileData.type || 文本/ X-java的;
var metadata = {
'title':文件名,
'mimeType':contentType
};

var base64Data = btoa(reader.result);
var multipartRequestBody =
delimiter +
'Content-Type:application / json\r\\\
\r\''+
JSON.stringify(metadata)+
分隔符+
'Content-Type:'+ contentType +'\r\\\
'+
'Content-Transfer-Encoding:base64 \\\\''+
'\r\\\
'+
base64Data +
close_delim;

var request = gapi.client.request(
{$ b $'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);




解决方案

尝试检出并试用快速入门

 < html> 
< head>
< script type =text / javascript>
//您的客户ID可通过Google
开发人员控制台https://console.developers.google.com
var CLIENT_ID ='< YOUR_CLIENT_ID> ;

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

/ **
*检查当前用户是否授权此应用程序。
* /
函数checkAuth(){
gapi.auth.authorize(
{
'client_id':CLIENT_ID,$ b $'scope':SCOPES。 join(''),
'immediate':true
},handleAuthResult);
}

/ **
*处理来自授权服务器的响应。
*
* @param {Object} authResult授权结果。
* /
函数handleAuthResult(authResult){
var authorizeDiv = document.getElementById('authorize-div');
if(authResult&&!authResult.error){
//隐藏认证用户界面,然后加载客户端库。
authorizeDiv.style.display ='none';
loadDriveApi();
} else {
//显示auth UI,允许用户通过
// //点击授权按钮来启动授权。
authorizeDiv.style.display ='inline';
}
}

/ **
*响应用户单击授权按钮启动授权流程。
*
* @param {Event}事件按钮单击事件。
* /
函数handleAuthClick(event){
gapi.auth.authorize(
{client_id:CLIENT_ID,scope:SCOPES,immediate:false},
handleAuthResult) ;
返回false;
}

/ **
*加载Drive API客户端库。
* /
函数loadDriveApi(){
gapi.client.load('drive','v3',listFiles);
}

/ **
*打印文件。
* /
函数listFiles(){
var request = gapi.client.drive.files.list({$ b $'pageSize':10,
'fields' :nextPageToken,files(id,name)
});

request.execute(function(resp){
appendPre('Files:');
var files = resp.files;
if(files&& amp; amp; ; files.length> 0){
for(var i = 0; i< files.length; i ++){
var file = files [i];
appendPre(file。 name +'('+ file.id +')');
}
} else {
appendPre('找不到文件');
}
});
}

/ **
*将pre元素附加到包含给定消息
*的主体作为其文本节点。
*
* @param {string}消息要放置在pre元素中的文本。
* /
函数appendPre(message){
var pre = document.getElementById('output');
var textContent = document.createTextNode(message +'\\\
');
pre.appendChild(textContent);
}

< / script>
< script src =https://apis.google.com/js/client.js?onload=checkAuth>
< / script>
< / head>
< body>
< div id =authorize-divstyle =display:none>
< span>授权存取Drive API< / span>
<! - 用户点击以启动授权序列的按钮 - >
< button id =authorize-buttononclick =handleAuthClick(event)>
授权
< / button>
< / div>
< pre id =output>< / pre>
< / body>
< / html>

使用Drive API时,您可以熟悉代码和一些必要步骤。希望它有帮助。


I'm trying to upload text typed into a Textarea to a Google Drive file (mimetype: text/x-java for java source code.)

I've tried to incorporate the update and insert methods mentioned in the Drive Rest Files API but keep getting 401 errors. The implementation can be found at https://jgloud.net.

Any help would be appreciated.

  // 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);
    }
  }
}

解决方案

try checking out and try the quickstart for 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>

This would be useful way to familiarize yourself to the code and some required steps when using Drive API. Hope it helps.

这篇关于使用Javascript将文本从Textarea保存到Google Drive的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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