繁体   English   中英

Google Drive API V3 Javascript-创建包含内容的文件

[英]Google Drive API V3 Javascript - Create File with Content

之前已经问过这个问题,但是答案是使用API​​ V2。 Google文档未阐明如何使用javascript客户端代码创建包含其内容的文件。 我尝试使用“节点”下列出的代码,但是,它仅创建文件,不插入任何内容。 这是我的代码:

  let fileMetadata = {
    'name': name,
    parents: [parentId]
  };

  let media = {
    mimeType: 'text/plain',
    body: 'content inside file'
  };

  gapi.client.drive.files.create({
    resource: fileMetadata,
    media,
    fields: 'id'
  })
  .then(response => {
    console.log('response: ', response);
  })
  .catch(() => {
    console.log('something is wrong');
  });

有人可以帮我将内容插入文件吗?

这个示例脚本怎么样? 在我的环境中,尽管gapi.client.drive.files.create()可以在Google云端硬盘上创建一个空文件,但它无法直接上传包含内容的文件。 我认为这可能无法上传包含multipart / related的文件和元数据,尽管将来的更新可能会解决此问题。 因此,现在,作为一种解决方法,我使用XMLHttpRequest。

在使用此示例脚本之前,请确认以下几点。

  • 根据您的情况,您已经能够使用gapi创建文件。 在我的脚本中,访问令牌是使用gapi检索的。
  • 使用此脚本时,请设置fileContent和元数据。

示例脚本:

在此示例脚本中,将在文件夹下创建一个包含内容的文本文件。

var fileContent = 'sample text'; // As a sample, upload a text file.
var file = new Blob([fileContent], {type: 'text/plain'});
var metadata = {
    'name': 'sampleName', // Filename at Google Drive
    'mimeType': 'text/plain', // mimeType at Google Drive
    'parents': ['### folder ID ###'], // Folder ID at Google Drive
};

var accessToken = gapi.auth.getToken().access_token; // Here gapi is used for retrieving the access token.
var form = new FormData();
form.append('metadata', new Blob([JSON.stringify(metadata)], {type: 'application/json'}));
form.append('file', file);

var xhr = new XMLHttpRequest();
xhr.open('post', 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id');
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.responseType = 'json';
xhr.onload = () => {
    console.log(xhr.response.id); // Retrieve uploaded file ID.
};
xhr.send(form);

要求正文:

在此脚本中, form如下。 这是使用Drive API的create方法发送到Google云端硬盘的。

------WebKitFormBoundaryxX0XmxgooMjdUECR
Content-Disposition: form-data; name="metadata"; filename="blob"
Content-Type: application/json

{"name":"sampleName","mimeType":"text/plain","parents":["#####"]}
------WebKitFormBoundaryxX0XmxgooMjdUECR
Content-Disposition: form-data; name="file"; filename="blob"
Content-Type: text/plain

sample text
------WebKitFormBoundaryxX0XmxgooMjdUECR--

在我的环境中,我确认这可以正常工作。 但是,如果这在您的环境中不起作用,对不起。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM