将图像存储到localStorage

时间:2013-11-22 09:40:18

标签: javascript html json html5

Hai iam目前正在使用页面从json获取图像并希望存储localy .. 这是我的代码......

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript" src="eventorig.json"></script>

</head>
<body>
    <img class="imageClass" src=""></img>
</body>
<script>
var url;

$(".imageClass").attr("src",localStorage.UrlImage);
for(var i in jsonData)
        {
            for(var j in jsonData[i].Events)
                {

        for(var key in  jsonData[i].Events[j].Images)  

                    {



        url=jsonData[i].Events[j].Images[key].ImageUrl;

    if(typeof(Storage)!=="undefined")
                    {

                localStorage.UrlImage=url;

                          }
                        else
                          {

   document.getElementById("result").innerHTML="Sorry, your browser does not support  
         web   storage...";

                          }


                    }
                }
    console.log($(".imageClass").attr("src"));      
        }
  </script>
    </html>

以下是我的json

       var jsonData={"ResponseCode":0,
       "ApiVersion":0,
        "Data":
         {"Events":

               [
            {
                "Id":1124,
                "ImageCaption":"Hip flask",
                "ImageUrl":"https://s3-ap-southeast-
                                      2.amazonaws.com/drugdetectionapp-
                                      media/1004/alcohol_para.jpg",
                "Description":"des",
                "DateUpdated":"2013-11-06T16:55:55"
            },
                        ]
我从它获取图像,但我不能存储它localy我搜索了很长一段时间我只使用canvas获得解决方案..这是我寻找除画布以外的解决方案 是否有可能??等待你的有价值的命令谢谢

2 个答案:

答案 0 :(得分:3)

您可以尝试通过二进制XMLHttpRequest下载imgage,然后将原始二进制数据转换为base64并存储它。

请注意相同的原始政策,请参阅http://en.wikipedia.org/wiki/Same-origin_policy

代码看起来应该类似于:

var req = new XMLHttpRequest();
req.open("GET", https://s3-ap-southeast-2.amazonaws.com/drugdetectionapp-media/1004/alcohol_para.jpg", true);
req.responseType = "arraybuffer";

req.onload = function (event) {
  var buffer = req.response;
  if (buffer) {
    var byteArray = new Uint8Array(buffer);
    // Maybe you could also use buffer directly here...
    var b64 = btoa(byteArray);
    localStorage.setItem("imageData", b64); 
  }
};
req.send(null);

}

答案 1 :(得分:0)

这里有一个示例,说明如何将图像转换为字符串,然后将其保存在localStorage中。有点复杂,但也许会帮助你。 How to store and retrieve image to localStorage?