Search code examples
javascriptgoogle-apigoogle-drive-apibase64google-api-js-client

Success upload to Google Drive but empty file when open (Still have size)


After convert image URL to base64 string, I tried to upload this base64 image to Goolge Drive, everything work fine: response code 200 and Goole Drive display this file in App/Web.

But when I open this image, it like Google change something on base64 string, so it can't read.

After download and convert image from GD to base64 string, I see that my original base64 string was change.

Before upload: https://anotepad.com/notes/nt6fct

File from Google Drive: https://anotepad.com/notes/ayg57q

Upload code:

testUploadFile(fileInfo, base64Data){
    const boundary = '-------314159265358979323846';
    const delimiter = "\r\n--" + boundary + "\r\n";
    const close_delim = "\r\n--" + boundary + "--";
    var contentType = fileInfo.type || 'application/octet-stream';
    var metadata = {
        'name': fileInfo.title,
        'mimeType': contentType
    };

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

    gapi.client.request({
        'path': '/upload/drive/v3/files',
        'method': 'POST',
        'params': {
            'uploadType': 'multipart'
        },
        'headers': {
            'Content-Type': 'multipart/related; boundary="' + boundary + '"'
        },
        'body': multipartRequestBody
    }).then(function(response){
        console.log(response);
    });
}

Something wrong @@ Could you please correct it? Thanks in advance!


Solution

  • This simple example might help you find the issue with your code.

    function createFile(){
    const boundary = '-------314159265358979323846';
    const delimiter = "\r\n--" + boundary + "\r\n";
    const close_delim = "\r\n--" + boundary + "--";
    
    var fileContent = 'It works :)';
    
    var metadata = {
        'name': 'myFile',
        'mimeType': 'text/plain\r\n\r\n'
    };
    
    var multipartRequestBody = delimiter +  'Content-Type: application/json\r\n\r\n' + JSON.stringify(metadata) + delimiter + 'Content-Type: ' + 'text/plain\r\n\r\n' + fileContent + close_delim;
    
    gapi.client.request({
        'path': '/upload/drive/v3/files',
        'method': 'POST',
        'params': {
            'uploadType': 'multipart'
        },
        'headers': {
            'Content-Type': 'multipart/related; boundary="' + boundary + '"'
        },
        'body': multipartRequestBody
    }).then(function(response){
        console.log(response);
    });
    }