URLs对象 blob URL

时间:2023-03-08 22:18:08
把指向数据的URL保存到file或者blob对象里,好处就是不需要先文件读取内容然后才能用。

function createObjectURL(blob){
if (window.URL){
return window.URL.createObjectURL(blob);
} else if (window.webkitURL){
return window.webkitURL.createObjectURL(blob);
} else {
return null;
}
}

返回一个URL字符串,指向内存地址,例如可以直接展示图片文件出来:
var filesList = document.getElementById(“files-list”);
EventUtil.addHandler(filesList, “change”, function(event){
var info = “”,
output = document.getElementById(“output”),
progress = document.getElementById(“progress”),
files = EventUtil.getTarget(event).files,
reader = new FileReader(),
url = createObjectURL(files[0]);
if (url){
if (/image/.test(files[0].type)){
output.innerHTML = “<img src=\”” + url + “\”>”;
} else {
output.innerHTML = “Not an image.”;
}
} else {
output.innerHTML = “Your browser doesn’t support object URLs.”;
}
});
直接把URL对象输出到img里,不需要把数据先读取到JavaScript。 img标签自己会从URL指向的内存地址拿图片

当不用的时候,应该清除掉,释放内存:
function revokeObjectURL(url){
if (window.URL){
window.URL.revokeObjectURL(url);
} else if (window.webkitURL){
window.webkitURL.revokeObjectURL(url);
}
}