Ajax Binary Response

前端 未结 4 957
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 08:04

Hi I\'m wondering if there\'s anyway to stream a binary response in AJAX? This would be an ultimate solution otherwise I would need to realize the binary image to a file th

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 08:37

    This is an extension to Tom Ashworth's response (which helped to put me on the right track with the issue I was facing). This allows you to just get the filestream (FileStreamResult if you are using asp.net mvc) and set it to the img src, which is cool.

    var oReq = new XMLHttpRequest();
    oReq.open("post", '/somelocation/getmypic', true );        
    oReq.responseType = "blob";
    oReq.onload = function ( oEvent )
    {
        var blob = oReq.response;
        var imgSrc = URL.createObjectURL( blob );                        
        var $img = $( '', {                
            "alt": "test image",
            "src": imgSrc
        } ).appendTo( $( '#bb_theImageContainer' ) );
        window.URL.revokeObjectURL( imgSrc );
    };
    oReq.send( null );
    

    The basic idea is that the data is returned untampered with, it is placed in a blob and then a url is created to that object in memory. See here and here. Note supported browsers.

提交回复
热议问题