0

How can I upload this blob file to a Google Drive folder that I have the folder ID:

var blob = new Blob([credentialText], {
    type: "text/plain;charset=utf-8;",
});

The documentation seems so unclear. I have checked this link but there is no example of how I can make a request... I also checked the CORS requests but doesn't help. I am so lost :(

Thanks in advance.

I tried this and it does work:

var createFile = function(name,text,parentId) {
    var auth_token = $rootScope.accessToken;

    const boundary = '-------314159265358979323846';
    const delimiter = "\r\n--" + boundary + "\r\n";
    const close_delim = "\r\n--" + boundary + "--";
    var mimeType = 'text/plain';
    var metadata = { 
      "name" : name,
      "mimeType": 'text/plain',
      "parents": [parentId]
    };  

    var multipartRequestBody =
    delimiter +  'Content-Type: application/json\r\n\r\n' +
    JSON.stringify(metadata) +
    delimiter + 'Content-Type: application/json\r\n\r\n' +
    text +
    close_delim;

    gapi.client.request({ 
        'path': '/upload/drive/v3/files/',
        'method': 'POST',
        'params': {'uploadType': 'multipart'},
        'headers': { 'Content-Type': 'multipart/form-data; boundary="' + boundary + '"', 'Authorization': 'Bearer ' + auth_token, },
        'body': multipartRequestBody 
    }).execute(function(file) { 
        console.log(file);
        console.log("Wrote to file " + file.name + " id: " + file.id); 
    }, function(error){
        console.log(error);
    }); 
}
phuwin
  • 3,130
  • 4
  • 26
  • 49

1 Answers1

0

After digging in these two previous questions (here and here), I found a solution by partly combining those questions:

var createTxtFile = function(name,text,parentId) {
    var auth_token = $rootScope.accessToken;

    const boundary = '-------314159265358979323846';
    const delimiter = "\r\n--" + boundary + "\r\n";
    const close_delim = "\r\n--" + boundary + "--";
    const mimeType = 'text/plain';

    var metadata = { 
      "name" : name,
      "mimeType": mimeType,
      "parents": [parentId]
    };  

    var multipartRequestBody =
    delimiter +  'Content-Type: application/json\r\n\r\n' +
    JSON.stringify(metadata) +
    delimiter + 'Content-Type:'+ mimeType+'\r\n\r\n' +
    text +
    close_delim;

    gapi.client.request({ 
        'path': '/upload/drive/v3/files/',
        'method': 'POST',
        'params': {'uploadType': 'multipart'},
        'headers': { 'Content-Type': 'multipart/mixed; boundary="' + boundary + '"', 'Authorization': 'Bearer ' + auth_token, },
        'body': multipartRequestBody 
    }).execute(function(file) { 
        console.log(file);
        console.log("Wrote to file " + file.name + " id: " + file.id); 
    }, function(error){
        console.log(error);
    }); 
}
Community
  • 1
  • 1
phuwin
  • 3,130
  • 4
  • 26
  • 49