【问题标题】:How to upload a file to google drive api with uploadType=resumable如何使用 uploadType=resumable 将文件上传到谷歌驱动器 API
【发布时间】:2020-09-03 21:50:24
【问题描述】:

我尝试按照可恢复上传类型的参数上传文件,得到状态200(OK),但文件没有上传。

  • 状态视图
GENERAL
Request URL: https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable
Request Method: POST
Status Code: 200 
Remote Address:
Referrer Policy: no-referrer-when-downgrade

参考:https://developers.google.com/drive/api/v3/manage-uploads#resumable

-这是我的代码结构,不胜感激

$.ajax({
    type: "POST",
    beforeSend: function(request) {
      request.setRequestHeader("Authorization", "Bearer" + " " + localStorage.getItem("accessToken"));
      request.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
    },
    url: "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",
    success: function (data) {
      console.log(data);
    },
    error: function (error) {
      console.log(error);
    },
    async: true,
    data: JSON.stringify({mimeType: "image/png", name: "sample" }),
    cache: false,
    processData: false,
    timeout: 60000
  });

【问题讨论】:

    标签: javascript ajax google-drive-api


    【解决方案1】:

    我相信你的目标和情况如下。

    • 您想使用 ajax 上传可恢复上传的文件。
    • 您的访问令牌可用于将文件上传到 Google 云端硬盘。
    • 您已经能够使用 Drive API。

    修改点:

    • 为了实现可续传,需要做如下流程。

      1. 为可恢复上传创建会话。
        • 这样,可以从作为端点的响应头中检索位置。这用于上传数据。
      2. 使用检索到的端点上传数据。
    • 在您的脚本中,可以创建会话。但是,不幸的是,该位置不是从响应标头中检索到的。我认为这是您的问题的原因。在这种情况下,作为下一步,需要使用该位置上传文件。

    • 在您的脚本中,文件内容未显示。所以在这个答案中,作为一个示例,我将文件输入和按钮标签添加为 HTML。

    修改脚本:

    <input type="file" id="file">
    <input type="button" value="upload" onclick="resumableUpload()">
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>
    
    const getData = (file) =>
      new Promise((resolve, reject) => {
        if (file) {
          const fr = new FileReader();
          fr.onload = f => resolve({filename: file.name, mimeType: file.type, fileSize: file.size, data: f.target.result});
          fr.onerror = err => reject(err);
          fr.readAsArrayBuffer(file);
        } else {
          resolve({});
        }
      });
    
    async function resumableUpload() {
      const accessToken = localStorage.getItem("accessToken");
      const file = document.getElementById("file").files[0];
      const fileObj = await getData(file);
      if (Object.keys(fileObj).length == 0) {
        console.log("No file.");
        return;
      }
    
      // 1. Create the session for the resumable upload..
      const metadata = {mimeType: fileObj.mimeType, name: fileObj.filename};
      $.ajax({
          type: "POST",
          beforeSend: function(request) {
            request.setRequestHeader("Authorization", "Bearer" + " " + accessToken);
            request.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
          },
          url: "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",
          success: function (data, _, r) {
            const location = r.getResponseHeader("location");
    
            // 2. Upload the data using the retrieved endpoint.
            $.ajax({
              type: "PUT",
              beforeSend: function(request) {
                request.setRequestHeader("Content-Range", `bytes 0-${fileObj.fileSize - 1}\/${fileObj.fileSize}`);
              },
              url: location,
              success: function (data) {
                console.log(data)
              },
              error: function (error) {
                console.log(error);
              },
              async: true,
              data: fileObj.data,
              cache: false,
              processData: false,
              timeout: 60000
            });
            
          },
          error: function (error) {
            console.log(error);
          },
          async: true,
          data: JSON.stringify(metadata),
          cache: false,
          processData: false,
          timeout: 60000
        });
    }  
    </script>
    

    注意:

    • 在这个脚本中,我修改了你的脚本。
    • 这是一个简单的示例脚本。所以请根据您的实际情况进行修改。

    参考资料:

    【讨论】:

    • 非常感谢@Tanaike,我已经实现了它并且它对我来说工作正常,我想知道如何更精确地检测需求,你有任何额外的指南可以吗给我?
    • @Vilmcode 感谢您的回复。我很高兴你的问题得到了解决。关于附加指南,我不确定。我可以在官方文档中知道如何使用它。 Ref对此我深表歉意。
    猜你喜欢
    • 2013-09-12
    • 2018-11-10
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    相关资源
    最近更新 更多