How to obtain and send binary data in ajax

Source: Internet
Author: User

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 );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.