Cant upload to subfolder on Google Drive with Google App Script

Viewed 338

I have a successful working version of my code that lets a user choose a file and upload to my Google Drive. I am using a method that uploads the file in chunks as a resumable upload to get around the 50mb limit. And its great! But it will only upload to the Root folder of my Google Drive!

I have been trying to implement this solution but the accepted answer is only a guess (admitted by the person who answered) and the Comments from the original poster that say what they did to get it working doesnt work for me either.

I have it currently as this for initialising the file to upload:

xhr.open("POST", "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&addParents=1XVNmZ7Q4vHLB7p9tTk0_rz7Z1VOwy_I8&removeParents=root");

This does not give an error, but just puts the file in the Root anyway.

I also tried changing the PUT request for the "resuming" but It either errors out with "file not found" if I dont match the original POST or if I do make them the same, It still just uploads to root!

The Google Documentation says what Im doing should work. what am I missing?

Full code here if it helps:

html:

<html>
  <head>
    <base target="_top">
      <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> 

    
    <title>Upload Files</title>
  </head>
  <body>
    <div class="container-fluid mt-5 d-flex justify-content-center">
  
 
 <div class="card py-2 px-5" style="width:550px">
  
   <div class="card-head my-4 border-bottom border-top">
    <h4 class="card-title">Upload File</h4>
   </div></center>
  
  <div class="card-body" id="resp">
   <form id="fileuploadForm">
   
     <li class="list-group-item"><input type="file" name="myFile" id="uploadfile"></li>
   
  </form>
  </div>
        <center><div id="progress" class="display-4"></div></center>

 </div>
 



  
 </div>

<script>
    const chunkSize = 5242880;

    $('#uploadfile').on("change", function() {
        var file = this.files[0];
        if (file.name != "") {
            var fr = new FileReader();
            fr.fileName = file.name;
            fr.fileSize = file.size;
            fr.fileType = file.type;
            fr.onload = init;
            fr.readAsArrayBuffer(file);
        }
    });

    function init() {
        $("#progress").text("Initializing.");
        var fileName = this.fileName;
        var fileSize = this.fileSize;
        var fileType = this.fileType;
        console.log({fileName: fileName, fileSize: fileSize, fileType: fileType});
        var buf = this.result;
        var chunkpot = getChunkpot(chunkSize, fileSize);
        var uint8Array = new Uint8Array(buf);
        var chunks = chunkpot.chunks.map(function(e) {
            return {
                data: uint8Array.slice(e.startByte, e.endByte + 1),
                length: e.numByte,
                range: "bytes " + e.startByte + "-" + e.endByte + "/" + chunkpot.total,
            };
        });
        google.script.run.withSuccessHandler(function(at) {
            var xhr = new XMLHttpRequest();
            xhr.open("POST", "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&addParents=1XVNmZ7Q4vHLB7p9tTk0_rz7Z1VOwy_I8&removeParents=root");
            xhr.setRequestHeader('Authorization', "Bearer " + at);
            xhr.setRequestHeader('Content-Type', "application/json");
            xhr.send(JSON.stringify({
                mimeType: fileType,
                name: fileName,
            }));
            xhr.onload = function() {
                doUpload({
                    location: xhr.getResponseHeader("location"),
                    chunks: chunks,
                });
            };
            xhr.onerror = function() {
                console.log(xhr.response);
            };
        }).getAt();
    }

    function doUpload(e) {
        var chunks = e.chunks;
        var location = e.location;
        console.log("this stuff: " + location);
        var cnt = 0;
        var end = chunks.length;
        var temp = function callback(cnt) {
            var e = chunks[cnt];
            var xhr = new XMLHttpRequest();
            xhr.open("PUT", location, true);
            xhr.setRequestHeader('Content-Range', e.range);
            xhr.send(e.data);
            xhr.onloadend = function() {
                var status = xhr.status;
                cnt += 1;
                console.log("Uploading: " + status + " (" + cnt + " / " + end + ")");
                $("#progress").text("Uploading: " + Math.floor(100 * cnt / end) + "%");
                if (status == 308) {
                    callback(cnt);
                    
                } else if (status == 200) {
                    $("#progress").text("Done.");
                } else {
                    $("#progress").text("Error: " + xhr.response);
                }
            };
        }(cnt);
    }

    function getChunkpot(chunkSize, fileSize) {
        var chunkPot = {};
        chunkPot.total = fileSize;
        chunkPot.chunks = [];
        if (fileSize > chunkSize) {
            var numE = chunkSize;
            var endS = function(f, n) {
                var c = f % n;
                if (c == 0) {
                    return 0;
                } else {
                    return c;
                }
            }(fileSize, numE);
            var repeat = Math.floor(fileSize / numE);
            for (var i = 0; i <= repeat; i++) {
                var startAddress = i * numE;
                var c = {};
                c.startByte = startAddress;
                if (i < repeat) {
                    c.endByte = startAddress + numE - 1;
                    c.numByte = numE;
                    chunkPot.chunks.push(c);
                } else if (i == repeat && endS > 0) {
                    c.endByte = startAddress + endS - 1;
                    c.numByte = endS;
                    chunkPot.chunks.push(c);
                }
            }
        } else {
            var chunk = {
                startByte: 0,
                endByte: fileSize - 1,
                numByte: fileSize,
            };
            chunkPot.chunks.push(chunk);
        }
        return chunkPot;
    }
    



    
</script>
</body>

</html>

GS:

function doGet() {
  return HtmlService.createHtmlOutputFromFile("index.html");
}

function getAt() {
  return ScriptApp.getOAuthToken();
}

// This commented line is used for enabling Drive API and adding a scope of "https://www.googleapis.com/auth/drive".
// So please don't remove this.
// DriveApp.createFile();

1 Answers

I believe your goal as follows.

  • You want to upload a file to the specific folder on Google Drive with the resumable upload.
  • You want to achieve this using Javascript by retrieving the access token from Google Apps Script.

For this, how about this answer?

Modification points:

  • From your replying comment, I could notice that you had used my script. In this case, I had updated the script. In the current stage, I have published a Javascript library for uploading the file with the resumable upload. In this answer, I used this.

Modified script:

HTML and Javascript side (index.html):

<form><input name="file" id="uploadfile" type="file" /></form>
<div id="progress"></div>

<script src="https://cdn.jsdelivr.net/gh/tanaikech/ResumableUploadForGoogleDrive_js@master/resumableupload_js.min.js"></script>

<script>
  document.getElementById("uploadfile").addEventListener("change", run, false);

  function run(obj) {
    google.script.run
      .withSuccessHandler(accessToken =>
        ResumableUploadForGoogleDrive(accessToken, obj)
      )
      .getAuth();
  }

  function ResumableUploadForGoogleDrive(accessToken, obj) {
    const file = obj.target.files[0];
    if (file.name != "") {
      let fr = new FileReader();
      fr.fileName = file.name;
      fr.fileSize = file.size;
      fr.fileType = file.type;
      fr.accessToken = accessToken;
      fr.readAsArrayBuffer(file);
      fr.onload = resumableUpload;
    }
  }

  function resumableUpload(e) {
    document.getElementById("progress").innerHTML = "Initializing.";
    const f = e.target;
    const resource = {
      fileName: f.fileName,
      fileSize: f.fileSize,
      fileType: f.fileType,
      fileBuffer: f.result,
      accessToken: f.accessToken,
      folderId: "###"  // <--- Please set the folder ID.
    };
    const ru = new ResumableUploadToGoogleDrive();
    ru.Do(resource, function(res, err) {
      if (err) {
        console.log(err);
        return;
      }
      console.log(res);
      let msg = "";
      if (res.status == "Uploading") {
        msg =
          Math.round(
            (res.progressNumber.current / res.progressNumber.end) * 100
          ) + "%";
      } else {
        msg = res.status;
      }
      document.getElementById("progress").innerText = msg;
    });
  }
</script>
  • In this case, please set the folder ID to resource.

Google Apps Script side (Code.gs):

function getAuth() {
  // DriveApp.createFile(blob) // This is used for adding the scope of "https://www.googleapis.com/auth/drive".
  return ScriptApp.getOAuthToken();
}

function showSidebar() {
  var html = HtmlService.createHtmlOutputFromFile("index");
  SpreadsheetApp.getUi().showSidebar(html);
}

Reference:

Added:

If you want to modify your current script, please modify as follows. In the case of the resumable upload, the file metadata is set at the initial request. Ref

From:

xhr.send(JSON.stringify({
    mimeType: fileType,
    name: fileName,
}));

To:

xhr.send(JSON.stringify({
    mimeType: fileType,
    name: fileName,
    parents: ["###"]  // <--- Please set the folder ID.
}));
Related