使用文件阅读器和blob显示图像

时间:2017-03-18 17:13:45

标签: javascript blob filereader

我希望使用javascript的fileReader api显示一组缩略图。我将向我的服务器发送请求,它将以字节流的形式响应。我通过本机xhr方法发送请求。但它不显示任何图像。

<!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>

任何帮助都将不胜感激。谢谢。

更新:正确的解决方案

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

1 个答案:

答案 0 :(得分:1)

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