javascript - 如何使用 googledrive api 将文件上传到 googledrive?

标签 javascript google-drive-api

我按照文档( https://developers.google.com/drive/api/v3/manage-uploads#http---single-request )进行操作,但它不起作用:

          var fileMetadata = {
            name: e.target.files[j].name,
            parents: this.currentDirectoryId ? [this.currentDirectoryId] : []
          }
          var media = {
            mimeType: e.target.files[j].type,
            body: e.target.files[j]
          }
          window.gapi.client.drive.files.create({
            resource: fileMetadata,
            media: media,
            fields: 'id, name, mimeType, createdTime'
          }).then(res => console.log(res))

文件已创建,但为空且名为“Untitled”,mimeType为“application/octet-stream”

最佳答案

问题和解决方法:

  • 当我测试gapi.client.drive.files.create时,似乎该方法虽然可以使用元数据创建新文件,但无法包含文件内容。因此,在这个答案中,为了通过包含文件元数据来上传文件,我想建议使用 Javascript 的 fetch 上传带有 multipart/form-data 的文件。在本例中,访问 token 由 gapi.auth.getToken().access_token 检索。

  • 不幸的是,从您的脚本中,我无法理解e.target。因此,在这个示例脚本中,我想提出用于上传文件的示例脚本,该文件是从输入标记中检索到的,并带有元数据。

示例脚本:

HTML 端:

<input type="file" id="files" name="file">

Javascript 方面:

const files = document.getElementById("files").files;

const file = files[0];
const fr = new FileReader();
fr.readAsArrayBuffer(file);
fr.onload = (f) => {
  const fileMetadata = {
    name: file.name,
    parents: this.currentDirectoryId ? [this.currentDirectoryId] : []  // This is from your script.
  }
  const form = new FormData();
  form.append('metadata', new Blob([JSON.stringify(fileMetadata)], {type: 'application/json'}));
  form.append('file', new Blob([new Uint8Array(f.target.result)], {type: file.type}));
  fetch('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart', {
    method: 'POST',
    headers: new Headers({'Authorization': 'Bearer ' + gapi.auth.getToken().access_token}),
    body: form
  }).then(res => res.json()).then(res => console.log(res));
};
  • 在此脚本中,从 input 标记检索的文件将通过 multipart/form-data 上传到 Google 云端硬盘。

注意:

  • 在此脚本中,假设您的授权脚本可用于将文件上传到 Google 云端硬盘。请小心这一点。
  • 在此答案中,作为示例脚本,文件是使用 uploadType=multipart 上传的。在本例中,最大文件大小为 5 MB。请小心这一点。当您要上传较大文件时,请勾选断点续传。 Ref

引用文献:

关于javascript - 如何使用 googledrive api 将文件上传到 googledrive?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65181932/

相关文章:

javascript - 有什么理由从外部调用 Backbone.View.render 吗?

javascript - AngularJS - ui-grid - 数据显示问题

javascript - 使用 mongoose 有条件地删除或添加文档数组中的元素

javascript - Firefox 中的 jQuery @ 按键检测

javascript - Google Apps 脚本中的 Google 云端硬盘共享对话框

javascript - 如何使用javascript找到图像的经纬度中间点?

javascript - 如何使用 google drive api 使文件可共享

java - 如何设置谷歌驱动器下载文件的位置?

python - 从 Jupyter 使用 Python 设置 Drive API 时出错

google-drive-api - 如何使用 Google Drive API 搜索自定义文件属性?