JavaScript实现写入文件到本地的方法【基于FileSaver.js插件】
程序员文章站
2022-11-17 11:30:36
本文实例讲述了javascript实现写入文件到本地的方法。分享给大家供大家参考,具体如下:
工作中有时需要通过 javascript 保存文件到本地,我们都知道 jav...
本文实例讲述了javascript实现写入文件到本地的方法。分享给大家供大家参考,具体如下:
工作中有时需要通过 javascript 保存文件到本地,我们都知道 javascript 基于安全的考虑,是不允许直接操作本地文件的。
ie 可以通过 vb 插件的方式进行,而 chrome 和 firefox 都不支持 javascript 向本地写入文件,所以 vb 插件的方式存在兼容性问题。
那有没有适合的方法呢?答案是肯定的,我们可以通过 filesaver.js 这个小插件实现我们的需求。下面看一段具体的代码吧:
/** * 下载文件 */ var downloadtextfile = function(mobilecode) { if(isempty(mobilecode)) { mobilecode = ''; } var file = new file([mobilecode], "手机号.txt", { type: "text/plain;charset=utf-8" }); saveas(file); }
这个示例是向本地存储一个名字叫“手机号.txt”的文本文件,采用的字符编码格式为“utf-8”,这样就避免的中文乱码的问题。聪明的你也赶快试试吧!
附 filesaver.js 文件的完整源码:
/* filesaver.js * a saveas() filesaver implementation. * 1.3.2 * 2016-06-16 18:25:19 * * by eli grey, http://eligrey.com * license: mit * see https://github.com/eligrey/filesaver.js/blob/master/license.md */ /*global self */ /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */ /*! @source http://purl.eligrey.com/github/filesaver.js/blob/master/filesaver.js */ var saveas = saveas || (function(view) { "use strict"; // ie <10 is explicitly unsupported if (typeof view === "undefined" || typeof navigator !== "undefined" && /msie [1-9]\./.test(navigator.useragent)) { return; } var doc = view.document // only get url when necessary in case blob.js hasn't overridden it yet , get_url = function() { return view.url || view.webkiturl || view; } , save_link = doc.createelementns("http://www.w3.org/1999/xhtml", "a") , can_use_save_link = "download" in save_link , click = function(node) { var event = new mouseevent("click"); node.dispatchevent(event); } , is_safari = /constructor/i.test(view.htmlelement) || view.safari , is_chrome_ios =/crios\/[\d]+/.test(navigator.useragent) , throw_outside = function(ex) { (view.setimmediate || view.settimeout)(function() { throw ex; }, 0); } , force_saveable_type = "application/octet-stream" // the blob api is fundamentally broken as there is no "downloadfinished" event to subscribe to , arbitrary_revoke_timeout = 1000 * 40 // in ms , revoke = function(file) { var revoker = function() { if (typeof file === "string") { // file is an object url get_url().revokeobjecturl(file); } else { // file is a file file.remove(); } }; settimeout(revoker, arbitrary_revoke_timeout); } , dispatch = function(filesaver, event_types, event) { event_types = [].concat(event_types); var i = event_types.length; while (i--) { var listener = filesaver["on" + event_types[i]]; if (typeof listener === "function") { try { listener.call(filesaver, event || filesaver); } catch (ex) { throw_outside(ex); } } } } , auto_bom = function(blob) { // prepend bom for utf-8 xml and text/* types (including html) // note: your browser will automatically convert utf-16 u+feff to ef bb bf if (/^\s*(?:text\/\s*|application\/xml|\s*\/\s*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) { return new blob([string.fromcharcode(0xfeff), blob], {type: blob.type}); } return blob; } , filesaver = function(blob, name, no_auto_bom) { if (!no_auto_bom) { blob = auto_bom(blob); } // first try a.download, then web filesystem, then object urls var filesaver = this , type = blob.type , force = type === force_saveable_type , object_url , dispatch_all = function() { dispatch(filesaver, "writestart progress write writeend".split(" ")); } // on any filesys errors revert to saving with object urls , fs_error = function() { if ((is_chrome_ios || (force && is_safari)) && view.filereader) { // safari doesn't allow downloading of blob urls var reader = new filereader(); reader.onloadend = function() { var url = is_chrome_ios ? reader.result : reader.result.replace(/^data:[^;]*;/, 'data:attachment/file;'); var popup = view.open(url, '_blank'); if(!popup) view.location.href = url; url=undefined; // release reference before dispatching filesaver.readystate = filesaver.done; dispatch_all(); }; reader.readasdataurl(blob); filesaver.readystate = filesaver.init; return; } // don't create more object urls than needed if (!object_url) { object_url = get_url().createobjecturl(blob); } if (force) { view.location.href = object_url; } else { var opened = view.open(object_url, "_blank"); if (!opened) { // apple does not allow window.open, see https://developer.apple.com/library/safari/documentation/tools/conceptual/safariextensionguide/workingwithwindowsandtabs/workingwithwindowsandtabs.html view.location.href = object_url; } } filesaver.readystate = filesaver.done; dispatch_all(); revoke(object_url); } ; filesaver.readystate = filesaver.init; if (can_use_save_link) { object_url = get_url().createobjecturl(blob); settimeout(function() { save_link.href = object_url; save_link.download = name; click(save_link); dispatch_all(); revoke(object_url); filesaver.readystate = filesaver.done; }); return; } fs_error(); } , fs_proto = filesaver.prototype , saveas = function(blob, name, no_auto_bom) { return new filesaver(blob, name || blob.name || "download", no_auto_bom); } ; // ie 10+ (native saveas) if (typeof navigator !== "undefined" && navigator.mssaveoropenblob) { return function(blob, name, no_auto_bom) { name = name || blob.name || "download"; if (!no_auto_bom) { blob = auto_bom(blob); } return navigator.mssaveoropenblob(blob, name); }; } fs_proto.abort = function(){}; fs_proto.readystate = fs_proto.init = 0; fs_proto.writing = 1; fs_proto.done = 2; fs_proto.error = fs_proto.onwritestart = fs_proto.onprogress = fs_proto.onwrite = fs_proto.onabort = fs_proto.onerror = fs_proto.onwriteend = null; return saveas; }( typeof self !== "undefined" && self || typeof window !== "undefined" && window || this.content )); // `self` is undefined in firefox for android content script context // while `this` is nsicontentframemessagemanager // with an attribute `content` that corresponds to the window if (typeof module !== "undefined" && module.exports) { module.exports.saveas = saveas; } else if ((typeof define !== "undefined" && define !== null) && (define.amd !== null)) { define("filesaver.js", function() { return saveas; }); }
ps:本站在线工具上面工具中的很多文件下载功能都是基于filesaver.js插件实现的,感兴趣的朋友可以查找参考一下。
更多关于javascript相关内容感兴趣的读者可查看本站专题:《javascript文件与目录操作技巧汇总》、《javascript查找算法技巧总结》、《javascript数据结构与算法技巧总结》、《javascript遍历算法与技巧总结》、《javascript错误与调试技巧总结》及《javascript数学运算用法总结》
希望本文所述对大家javascript程序设计有所帮助。