网页设计学习笔记

HTML,CSS,JavaScript

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: :: 管理 ::
  119 随笔 :: 0 文章 :: 1 评论 :: 0 引用

利用 W3C 草案中的 Blob,我们有了新的方法来保存本地文件。例如(查看效果):

function doSave(value, type) {
    var blob;
    if (typeof window.Blob == "function") {
        blob = new Blob([value], {type: type});
    } else {
        var BlobBuilder = window.BlobBuilder || window.MozBlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder;
        var bb = new BlobBuilder();
        bb.append(value);
        blob = bb.getBlob(type);
    }
    var URL = window.URL || window.webkitURL;
    var bloburl = URL.createObjectURL(blob);
    location.href = bloburl;
}

doSave("Hello Blob!", "text/latex"); 

上述的代码适用于 Firefox 6,Chrome 8 和 IE 10 及其以上的浏览器。其中 BlobBuilder 在浏览器最新版本中已经被 Blob 取代。同样地,对于 Chrome,在本地网页中无法使用此功能。

上面的方法得到的保存文件窗口无法设定文件名,用起来有些别扭。对于 Chrome 14 及以上的浏览器,我们可以利用它支持的 a.download 属性来设定要保存的文件名。(2013 年 2 月 8 日更新:Firefox 20 中也支持 a.download 了)而对于 IE 10,我们可以用 navigator 的 msSaveBlob() 方法来设定要保存的文件名。为此,我们可以将上面的例子稍微修改为(查看效果):

function doSave(value, type, name) {
    var blob;
    if (typeof window.Blob == "function") {
        blob = new Blob([value], {type: type});
    } else {
        var BlobBuilder = window.BlobBuilder || window.MozBlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder;
        var bb = new BlobBuilder();
        bb.append(value);
        blob = bb.getBlob(type);
    }
    var URL = window.URL || window.webkitURL;
    var bloburl = URL.createObjectURL(blob);
    var anchor = document.createElement("a");
    if ('download' in anchor) {
        anchor.style.visibility = "hidden";
        anchor.href = bloburl;
        anchor.download = name;
        document.body.appendChild(anchor);
        var evt = document.createEvent("MouseEvents");
        evt.initEvent("click", true, true);
        anchor.dispatchEvent(evt);
        document.body.removeChild(anchor);
    } else if (navigator.msSaveBlob) {
        navigator.msSaveBlob(blob, name);
    } else {
        location.href = bloburl;
    }
}

doSave("Hello Blob!", "text/latex", "hello.tex"); 

相应地,要在浏览器中打开本地文件,可以看这篇文章

参考资料:
[1] File API - W3C Working Draft
[2] BlobBuilder - W3C Working Draft
[3] BlobBuilder - MDN
[4] Blob - MDN
[5] File API - MSDN
[6] When can I use BlobBuilder API?
[7] When can I use Blob URLs?
[8] window.URL.createObjectURL - MDN
[9] window.URL.revokeObjectURL - MDN
[A] createObjectURL method - MSDN
[B] Downloading resources in HTML5: a[download] - HTML5Rocks
[C] FileSaver.js demo
[D] How to save files locally using BlobBuilder and msSaveBlob - MSDN
[E] Creating Files through BlobBuilder - IEBlog
[F] HTML5的File API应用
[G] Chrome WebKitBlobBuilder doesn't append data
[H] Don't Build Blobs, Construct Them - HTML5Rocks Updates
[I] <a> - HTML | MDN #attr-download
[J] Bug 676619 - Implement proposed download attribute - Mozilla

posted on 2012-05-27 20:20  zoho  阅读(...)  评论(...编辑  收藏