Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send binary data via JQuery Ajax PUT method

I am new to JQuery and I want to use JQuery Ajax to upload some files to server, Only in PUT method. when I send some binary file(such as gif or jpeg) to my server, upload succeed, but the content of binary data was changed(it's always bigger than original file size). I try to change the content-type or the type of file result, but still not work. Anyone knows how to fix this?

PS: I cannot encode the binary file's content into other form, because I cannot touch the code of server.

var reader = new FileReader();

reader.onloadend = (function(Thefile) {

    $.ajax({
        url: url,
        processData:false,
        //contentType:"application/octet-stream; charset=UTF-8",
        data: file.result,
        type: 'PUT',
        success : function(){console.log("OK!");},
        error : function(){console.log("Not OK!");}
    }); 
})(file);

reader.readAsBinaryString(file);
like image 888
Ding Avatar asked Jul 12 '12 09:07

Ding


People also ask

Can AJAX use PUT method?

Approach: To make a PUT or DELETE requests in jQuery we can use the . ajax() method itself. We can specify the type of request to be put or delete according to the requirement as given in the example below.

How do you send binary data?

Sending binary dataThe send method of the XMLHttpRequest has been extended to enable easy transmission of binary data by accepting an ArrayBuffer , Blob , or File object. The following example creates a text file on-the-fly and uses the POST method to send the "file" to the server.


1 Answers

Most (all?) browsers will automatically convert string datatypes to UTF-8 when sending them via an XMLHttpRequest. When you read the file as a binary string, you're given exactly that: a JavaScript string object where each character is a value between 0 and 255.

To force the AJAX request to send binary encoded data, the data parameter must be an ArrayBuffer, File, or Blob object.

If you need access to the contents of the file before sending, you can convert the binary string to an ArrayBuffer with the following code:

var arrBuff = new ArrayBuffer(file.result.length);
var writer = new Uint8Array(arrBuff);
for (var i = 0, len = file.result.length; i < len; i++) {
    writer[i] = file.result.charCodeAt(i);
}

And you'd pass the arrBuff instance to the AJAX function. Otherwise, you should be able to pass the File object itself into the AJAX function without all of your FileReader code.

like image 104
Brendan Berg Avatar answered Sep 21 '22 23:09

Brendan Berg