0

I want to use a FileReader to POST an Excel file to my interface. It all works (as in there are no errors), except that the data sent seems to be mangled somewhere. When checking the wire, I can see the POST has a Content-Length of 11910 bytes, while my uploaded file is only 8852 bytes large.

This is the Javascript code:

function readfile() {
    // #excelFile is a simple <input type="file">
    var file = $("#excelFile")[0].files[0];

    var reader = new FileReader();
    reader.addEventListener("load", (event) => {
        restPutPost("post", "rest/mapping", reader.result, 
        function(data) {
            console.log(`File ${file.name} uploaded.`);
        }, 
        function(xhr, status, error) {
            console.log(`Upload failed: ${error}`);
        }, 
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    });

    reader.readAsBinaryString(file);
}

and the restPutPost is a convenience function I wrote:

function restPutPost(method, url, body, callback = null, errorcallback = null, contenttype = "application/json") {
    actualbody = body;
    if (contenttype == "application/json") {
        actualbody = body != null?JSON.stringify(body): null;
    }

    $.ajax({
        type: method,
        url: url,
        headers: {
            Accept: "application/json"
        },
        data: actualbody,
        contentType: contenttype,
        success: function (data) {
            if (callback != null) {
                callback(data);
            }
        },
        error: function (xhr, status, error) {
            if (errorcallback != null) {
                errorcallback(xhr, xhr.status, error);
            }
        }
    });
}
Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195

1 Answers1

0

I ran into a few issues with sending binary data. First, the jQuery XHR does not guarantee the data is untouched. Second, JSON does not support binary data.

So, to fix the issue, I decided to transform the binary data into Base64, and put that into a JSON object:

var obj = {}
obj["exceldata"] = btoa(reader.result);

restPutPost("post", "rest/mapping", obj);

This way, my entire interface stays JSON and I can still send binary data.

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195