Ajax request binary Stream picture file XMLHttpRequest best practices for requesting and processing binary stream data

Source: Internet
Author: User
Tags builtin

Written in front: from the request to the perfect solution to the problem, the implementation process is tortuous.

Requirement: In the framework of a fully decoupled schema after the front (web client) end (Restful service), the WebClient needs to request the image file (binary stream) returned by the Service and is displayed on the client side.

The first step of thinking: to get this demand, based on the arrogance of the programmer, thinking about the display image, jquery Ajax direct GET request will return data assigned to the IMG tag src attribute, so easy~

Do not know the sky after the boy start code, after a few minutes to give the following code, and confident full of preparation test.

            $.ajax ({            //    method: "GET",            //    url:serverurlbase + "/server/images/" + mapid + "/files/png",//cross-domain, Request will return stream file PNG image            //    beforesend:function (XHR) {            //        Xhr.setrequestheader ("Client_type", "Desktop_web" );        Xhr.setrequestheader ("Desktop_web_access_key", _desktop_web_access_key);    },            //    success:function (data) {            //        //$ ("#remoteimg"). attr ("url", data);            //    }            //});

In Visual Studio, select the file to view in the browser.

What is this, a ~!!!!!!!!!!!!!!!? Not meet the expectations AH ~ ~ ~!!!!!!!!!

second thought: the backend that kid gave the API must have a problem. Let's start with a tool test.

Open Chorme, open the loaded Postman component, enter the request address, and click Send. Wait two seconds a large picture file shows up ~ ~

The third step: the back end that kid's interface is normal. The problem is on my own (the expression is getting serious.) Console.log the requested data.

After a few minutes of stalling, I took a trip, the browser how the card dead. Wait a minute. The data is printed out:

What a good boy, my child (Orthodox Huainan dialect).

The fourth step is thinking : How is this data. Postman in the back of the picture ah my how this, to see what the Postman returned is the data.

In postman, select the picture-right-click to check as shown:

Fifth Step: Why my data is different from postman data. Why is it garbled? No, what is the data returned by Ajax? Is the code changed? Don't support binary streams?

While thinking about opening the jquery website (complaining about the jquery website really slow, w3school really superficial) find AJAX datatype data types

Found that there is no binary data option, that is, the returned data is returned by default in text form.

Complaining: jquery has been doing this for so long an Ajax method still stays in the version of XMLHttpRequest 1 a few years ago, amazing not supporting streaming files!!!

How can I push my back and forth completely to isolate the thought ~ ~. Forget not to complain, sure enough to rely on others, can only write their own.

The landlord vaguely remember XMLHttpRequest 2 standard in support stream file, and should use Xhr.response as return instead of ResponseText. So start writing to:

var url = serverurlbase + "/server/images/" + mapid + "/files/png";
var xhr = new XMLHttpRequest (); Xhr.open (' GET ', url, true);//get request, request address, whether asynchronous
Xhr.setrequestheader ("Client_type", "Desktop_web"); Xhr.setrequestheader ("Desktop_web_access_key", _desktop_web_access_key);
Xhr.onload = function () { if (this.status = =) { var data = This.response;
Todo............................................... How to receive data.
} } xhr.send ();

The Sixth step thinking: this should be feasible, but how to deal with the requested data????? The problem. Yes, the new HTML5 feature mentions a Blob object. Try.

Check the 4.6.9 the attribute to learn that the response return type should be used by checking the relevant BLOB data

Add the following code where the request succeeds:

var blob=new blob ();

Blob=this.response;

Now that the binary data has been taken, put it in an HTML tag and it should be an IMG tag then: The code should be

var img = document.createelement ("img");

img.src = window.  Url.createobjecturl (BLOB); There is a problem in loading the BLOB into IMG because the BLOB is too general to have a performance impact how should it be released after loading:

Img.onload = function (e) {

Window. Url.revokeobjecturl (IMG.SRC);//release.
};

Then put the IMG in a div container and you can do it.

$ ("#imgcontainer"). HTML (IMG); Yes, request processing should be the case.

Then our final code is as follows:

            var url = serverurlbase + "/server/images/" + mapid + "/files/png";            var xhr = new XMLHttpRequest ();            Xhr.open (' GET ', url, true);            Xhr.responsetype = "blob";            Xhr.setrequestheader ("Client_type", "Desktop_web");            Xhr.setrequestheader ("Desktop_web_access_key", _desktop_web_access_key);            Xhr.onload = function () {                if (this.status = =) {                    var blob = this.response;                    var img = document.createelement ("img");                    Img.onload = function (e) {                        window. Url.revokeobjecturl (IMG.SRC);                     };                    img.src = window. Url.createobjecturl (BLOB);                    $ ("#imgcontainer"). HTML (IMG);                    }            }            Xhr.send ();

Conclusion: This landlord solves the problem of loading binary stream. In conjunction with the Ajax cross-domain request mentioned in the previous article, it is a step closer to the implementation of the concept of complete separation of the front and back ends. There are, of course, many issues to consider in the face of security.

In this process, let's hug to realize that the high-level package (Ajax) is good, but for some special requests can not be processed (request flow file), so also need to master the underlying principle, in order to face the demanding requirements.

Summary code:

VarXhr=NewXMLHttpRequest();Xhr.Open(The Get"Url,True);Xhr.Responsetype=The Blob";Xhr.OnLoad=function(){If(This.Status==200){VarBlob=This.ResponseVarImg=Document.CreateElement(The img "); img. onload = function  (e) { Window. url. revokeobjecturl (img. Src }; img. src = window. Url. createobjecturl (blob   
 $ ("#imgcontainer"). HTML (IMG); 
< span class= "operand" > < Span class= "Paren" > } } xhr. send (        

Resources:

Http://api.jquery.com/jQuery.ajax/jquery Ajax API

Https://xhr.spec.whatwg.org/xmlhttprequest specification

https://xhr.spec.whatwg.org/#the-responsetype-attribute responsetype return type support

http://www.zhangxinxu.com/wordpress/2013/10/understand-domstring-document-formdata-blob-file-arraybuffer/ XMLHttpRequest related learning.

http://www.ruanyifeng.com/blog/2012/09/xmlhttprequest_level_2.html XMLHttpRequest User Guide

Category: HTML5 Css3,javascript

Ajax request binary Stream picture file XMLHttpRequest best practices for requesting and processing binary stream data

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.