Posting File Input as FileReader Binary Data through AJAX Post

无人久伴 提交于 2019-11-27 18:10:49

Simply sending the file reference as data (with processData: false) did the job for me at least:

$('#_testButton').bind('click', function () {
    var file = document.getElementById('_testFile').files[0];

    $.ajax({
        url: "/attachmentURL",
        type: "POST",
        data: file,
        processData: false
    });
});

It is described here: https://developer.mozilla.org/en/DOM/XMLHttpRequest/Sending_and_Receiving_Binary_Data#section_3

Sending a string (even if that string represents binary data) will not work because the browser will forcibly turn it into unicode and encode as utf-8 as specified which will corrupt the binary data:

If data is a string Let encoding be UTF-8.

Let mime type be "text/plain;charset=UTF-8".

Let the request entity body be data converted to Unicode and encoded as UTF-8.

Sending a file reference (blob) will do this:

If data is a Blob If the object's type attribute is not the empty string let mime type be its value.

Let the request entity body be the raw data represented by data.

var file;

        $('#_testFile').on("change", function (e) {
            file = e.target.files[0];
        });
        $('#_testButton').click(function () {
            var serverUrl = '/attachmentURL';

            $.ajax({
                type: "POST",
                beforeSend: function (request) {
                    request.setRequestHeader("Content-Type", file.type);
                },
                url: serverUrl,
                data: file,
                processData: false,
                contentType: false,
                success: function (data) {
                    console.log("File available at: ", data);
                },
                error: function (data) {
                    var obj = jQuery.parseJSON(data);
                    alert(obj.error);
                }
            });
        });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!