Posting File Input as FileReader Binary Data through AJAX Post

前端 未结 2 871
执笔经年
执笔经年 2020-12-04 16:38

I am trying to post an attachment uploaded to an HTML file input to a web page through a rest API. The API documentation states that the post is a straight binary content as

相关标签:
2条回答
  • 2020-12-04 17:18

    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.

    0 讨论(0)
  • 2020-12-04 17:18

    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);
                    }
                });
            });
    
    0 讨论(0)
提交回复
热议问题