如何使用Google Drive API将文件上传到Google Drive?

如何使用Google Drive API将文件上传到Google Drive?

问题描述:

我按照文档中的说明进行操作(https://developers.google.com/drive/api/v3/manage-uploads#http---single-request ),但无效:

I did as in the documentation (https://developers.google.com/drive/api/v3/manage-uploads#http---single-request), but it doesn't work:

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

文件已创建,但为空,名为无标题".带有mimeType应用程序/八位字节流"

File is created, but empty and named "Untitled" with mimeType "application/octet-stream"

问题和解决方法:

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

    Issue and workaround:

    • When I tested gapi.client.drive.files.create, it seems that although this method can create new file with the metadata, the file content cannot be included. So in this answer, in order to upload a file by including the file metadata, I would like to propose to upload a file with multipart/form-data using fetch of Javascript. In this case, the access token is retrieved by gapi.auth.getToken().access_token.

      很遗憾,从您的脚本中,我无法理解 e.target .因此,在这个示例脚本中,我想提出一个示例脚本,用于上传带有元数据的文件,该文件是从input标签检索的.

      Unfortunately, from your script, I couldn't understand about e.target. So in this sample script, I would like to propose the sample script for uploading a file, which is retrieved from the input tag, with the metadata.

      <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云端硬盘.
        • In this script, the file retrieved from input tag is uploaded to Google Drive with multipart/form-data.
          • 在此脚本中,假定您的授权脚本可用于将文件上传到Google云端硬盘.请注意这一点.
          • 在此答案中,作为示例脚本,使用 uploadType = multipart 上传文件.在这种情况下,最大文件大小为5 MB.请注意这一点.要上传大文件时,请检查可恢复的上传.参考
          • In this script, it supposes that your authorization script can be used for uploading a file to Google Drive. Please be careful this.
          • In this answer, as a sample script, the file is uploaded with uploadType=multipart. In this case, the maximum file size is 5 MB. Please be careful this. When you want to upload the file with the large size, please check the resumable upload. Ref