Search code examples
javascriptgoogle-apigoogle-apis-explorer

FileReader - How to change the character encoding from UTF-8 to ANSI


I am trying to upload files to Google Drive through the API provided for the product. However, I think there is a problem with the encoding - in particular, the FileReader.readAsText() function.

I tried adding the optional parameter for encoding to make it look like r.readAsText(f,'ANSI') but it seems to not work.

The readAsText() function defaults to UTF-8 encoding for some weird reason. When I try to upload image files with UTF-8 encoding, they're corrupted and do not open properly.

 function readFile(evt) {
            var fData = [];
            var f = evt.target.files[0];
            if (f) {
                var r = new FileReader();
                r.readAsText(f);
                fData.unshift(f.name, f.type);
                var myInt = setInterval(function() {
                    if (r.readyState == 2) {
                        fData.push(r.result);
                        uploadFiles(fData);
                        clearInterval(myInt);
                    }
                }, 50);
            } else {
                alert("Failed to load file");
            }

        }


        function uploadFiles(dataArray,callback) {
                const boundary = '-------314159265358979323846';
                const delimiter = "\r\n--" + boundary + "\r\n";
                const close_delim = "\r\n--" + boundary + "--";

                const contentType = 'application/json';

                var metadata = {
                    'name': dataArray[0],
                    'mimeType': dataArray[1]
                };

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

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

        document.getElementById('upFile').addEventListener('change', readFile, false);

Solution

  • You want to upload files to Google Drive using Drive API by JavaScript. How about this workaround? In this workaround, the file is converted to base64 and uploaded to Google Drive.

    Modification points :

    • Use readAsDataURL() instead of readAsText().
    • Define data as base64 in request body.

    Modified script :

    Please modify 2 parts as follows.

    1. From :
    r.readAsText(f);
    
    1. To :
    r.readAsDataURL(f);
    
    2. From :
    var multipartRequestBody =
        delimiter +
        'Content-Type: application/json\r\n\r\n' +
        JSON.stringify(metadata) +
        delimiter +
        'Content-Type: ' + contentType + '\r\n\r\n' +
        dataArray[2] +
        close_delim
    
    2. To :
    var multipartRequestBody =
        delimiter +
        'Content-Type: application/json\r\n\r\n' +
        JSON.stringify(metadata) +
        delimiter +
        'Content-Type: ' + contentType + '\r\n' + // Modified
        'Content-Transfer-Encoding: base64\r\n\r\n' + // Added
        dataArray[2].split(",")[1] + // // Modified
        close_delim
    

    Reference :

    Also I have experienced the same situation with you. At that time, I resolved this using base64.