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

时间:2018-08-09 21:18:55

标签: javascript file google-drive-api google-api-js-client

此问题曾被问过,但答案是使用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');
  });

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

1 个答案:

答案 0 :(得分:2)

这个示例脚本怎么样?在我的环境中,尽管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 Drive的。

------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--

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