使用文件 reader 和 blob 显示图像

displaying images using file reader and blob

我想使用 fileReader 显示一组缩略图图像 api of javascript.I 将向我的服务器发送请求,它会以 bytes.I 流响应 我正在通过本机发送请求xhr methods.But 它没有显示任何图像。

<!DOCTYPE HTML>
<html>
    <head>
        <script type="text/javascript" src="/js/jquery-2.1.1.js"></script>
        <script>
            var thumbURL = ['https://domainname.com/api/th/1','https://domainname.com/api/th/2','https://domainname.com/api/th/3','https://domainname.com/api/th/4','https://domainname.com/api/th/5','https://domainname.com/api/th/6'];
            (function(){
            for(var i=0;i<thumbURL.length;i++){
                var oReq = new XMLHttpRequest();
                 oReq.open("GET", thumbURL[i]);
                 oReq.responseType = "blob";
                 oReq.onload = function(oEvent) {

                    if (this.status == 200) {

                    var fileReader = new window.FileReader();
                    fileReader.readAsDataURL(this.response);
                    var response=fileReader.result;
    $("#thumbnails").append("<img src="+response+"></div>");
                    }
                };


                 oReq.send();
            }

            })();

        </script>   
    </head>
    <body>

        <div id="thumbnails"></div>

    </body>
</html>

任何帮助都将大大提前appreciated.Thanks。

更新:正确的解决方案

<html>
    <head>
    <script type="text/javascript" src="/js/jquery-2.1.1.js"></script>
    <script>
    var thumbURL = ['https://domainname.com/api/th/1','https://domainname.com/api/th/2','https://domainname.com/api/th/3','https://domainname.com/api/th/4','https://domainname.com/api/th/5','https://domainname.com/api/th/6'];

    (function(){
    for(var i=0;i<thumbURL.length;i++){
    var oReq = new XMLHttpRequest();
    oReq.open("GET", thumbURL[i]);
    oReq.responseType = "blob";
    oReq.onload = function(oEvent) {
    if (this.status == 200) {
    var filereader=new window.FileReader();
    filereader.readAsDataURL(this.response);
    filereader.addEventListener("load",function() {
    var response=filereader.result;
    $("#thumbnails").append("<img src="+response+"></div>"); 
    },false); 
    }
    };
    oReq.onerror=function(e){
    alert("error");
    };

    oReq.send();
    }


    })();
    </script> 
    </head>
    <body>
    <div id="thumbnails"></div>

    </body>
    </html>

FileReader API 是异步的,因此您必须添加一个加载处理程序并在触发时添加结果:

var fileReader = new window.FileReader();
fileReader.onload = function() {   // need load handler
  var response=this.result;
  $("#thumbnails").append("<img src="+response+"></div>");
};
fileReader.readAsDataURL(this.response);

无论如何我都建议跳过转换部分。直接使用 blob 不仅可以节省内存,而且速度更快。您只需手动创建图像元素,例如:

oReq.onload = function(oEvent) {
  if (this.status === 200) {
    var img = new Image;
    img.src = (URL || webkitURL).createObjectURL(this.response);
    $("#thumbnails").append(img);  // todo: append the </div> separately
  }
};