When ajax is used to obtain binary data from the server, you need to use overrideMimtType to set the request header so that the browser does not modify the data to be read. The method is as follows:
Var xhr = new XMLHttpRequest ();
Xhr. onreadystatechange = function (){
If (xhr. readyState ===4 & xhr. status === 200 ){
Var imgdata = xhr. response;
}
}
Xhr. open ("GET", url, true );
Xhr. overrideMimeType ("text/plain; charset = x-user-defined ");
Xhr. send (null );
In addition, xhr. response is used to obtain binary data, instead of responseText.
If you need to send binary data through ajax POST, you need to change the high binary data to 0 before sending. Generally, you need to add a method in XMLHttpRequest to achieve this:
XMLHttpRequest. prototype. sendAsBinary = function (datastr ){
Function byteValue (x ){
Return x. charCodeAt (0) & 0xff;
}
Var ords = Array. prototype. map. call (datastr, byteValue );
Var ui8a = new Uint8Array (ords );
This. send (ui8a. buffer );
}
Var bindata = binary data;
Xhr. open ("POST", url );
Xhr. sendAsBinary (bindata );