Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
844 views
in Technique[技术] by (71.8m points)

jquery - Posting File Input as FileReader Binary Data through AJAX Post

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 the body of the HTTP request, not a form file upload.

My code is as follows:

$('#_testButton').bind('click', function () {
    var file = document.getElementById('_testFile').files[0]
    var reader = new FileReader();
    reader.onload = function () {
        $.ajax({
            url: '/attachmentURL',
            type: 'POST',
            data: reader.result
        })
    }
    reader.readAsBinaryString(file)
})

I need this to work for a number of different mimeTypes, so I didn't declare it in the code above. However, I have tried declaring contentType:'application/msword' for a .doc file and also tried processData:false and contentType:false.

The data is being posted where it should. However, when I open the file, I get a message that says mimeType:application/x-empty with an empty file OR a file with a bunch of binary characters. I've tried .doc files and a pdf files and the result is the same for both.

Does anyone have a clue what I can change to make this work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...