工作中有时需要通过 JavaScript 保存文件到本地,我们都知道 JavaScript 基于安全的考虑,是不允许直接操作本地文件的。
IE 可以通过 VB 插件的方式进行,而 Chrome 和 firefox 都不支持 JavaScript 向本地写入文件,所以 VB 插件的方式存在兼容性问题。
那有没有适合的方法呢?答案是肯定的,我们可以通过 FileSaver.js 这个小插件实现我们的需求。下面看一段具体的代码吧:

1
2
3
4
5
6
7
8
9
10
11
/**
 * 下载文件
 */
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 文件的完整源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
/* 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;
  });
}

  

JavaScript写入文件到本地相关推荐

  1. 解决IE8上传文件时javascript取文件的本地路径的问题C:\fakepath\..

    IE8上传文件时javascript读取文件的本地路径的问题("C:\fakepath\")的解决方案 前一阵把IE6升级到了IE8,没想到一个网站里面的上传图片时用JavaScr ...

  2. html5加js实现本地文件读取和写入并获取本地文件路径

    HTML5提供了一台API可以实现文件的读写,文件读取利用API是FileReader 代码如下: 读取本地文件 <!doctype html> <html lang="e ...

  3. JavaScript 获取上传文件的本地绝对路径

    一直苦恼于在表单提交时获得上传文件的本地绝对路径. 由于javascript是在浏览器环境运行的脚本语言,所以javascript的权限很低,不能操作本地资源,这样的好处是安全性提高了,但是也带来了开 ...

  4. 如何创建文件并用Java写入文件?

    用Java创建和写入(文本)文件的最简单方法是什么? #1楼 这是一个用于创建或覆盖文件的小示例程序. 它是长版本,因此更容易理解. import java.io.BufferedWriter; im ...

  5. PC端下载文件到本地

    最新更新时间:2021年08月12日14:42:40 <猛戳-查看我的博客地图-总有你意想不到的惊喜> 本文内容:前端开发过程中,经常会遇到下载文件到本地的需求,用户点击一个按钮,浏览器会 ...

  6. php选取远程文件到本地,PHP实现的一个保存远程文件到本地的函数分享

    最近遇到了PHP远程图片本地话的问题,查了查手册发现file_get_contents()和file_put_contents()可以解决这个问题.思路很简单,将远程文件读入字符串中,然后按照规则写入 ...

  7. android 保存文件到本地可见_android 日记log保存到本地简单方法

    安卓日常开发中,经常需要打印日记,经常需要把log输入到本地查看,本demo是把日记输出到本地的简单示例: 1.初始化保存路径(实例中为SD卡下: /storage/emulated/0/interp ...

  8. python如何读写文件-Python之写入文件(1)

    一.写入文件 保存数据也是在各个编程语言中常用的操作,将数据写入到文件中是常用的操作,你可以将程序运行中的一些临时输出保存至文件中,以便后续打开文件查看,也可以把这些文件读入程序中来操作其中的数据. ...

  9. IE浏览器上传文件时本地路径变成”C:\fakepath\”的问题

    IE浏览器上传文件时本地路径变成"C:\fakepath\"的问题 博客分类: javascript HTML 在使用<input id="file_upl&quo ...

  10. MapReduce基础开发之五分布式下载ftp文件到本地再迁移到hdfs

    为利用Hadoop集群平台的分布存储和计算能力,基于MapReduce将ftp文件分布式下载并上传到HDFS中. 1.文件移动流程:ftp服务器->datanode本地目录->HDFS目录 ...

最新文章

  1. 新来的同事问我 where 1=1 是什么意思
  2. Docker部署配置相关使用总结
  3. Hello World探究
  4. Effective Java之考虑用序列化代理代理序列化实例(七十八)
  5. wrapper怎么用_用责任链模式设计拦截器
  6. 组网胖模式_胖瘦AP组网优劣对比,你知道吗?
  7. python识别发票二维码_python如何实现二维码的生成和识别
  8. 基于ZYNQ FPGA实现8路ADC数据采集存储(AD7606)
  9. win10自带虚拟机安装CentOS7系统(转)
  10. 15条经典实用的网站优化技巧
  11. 谭晓生:如何面对IoT时代的安全新挑战?
  12. Python | OpenCV简单生成调色板
  13. 英语微课-Speaking Confidently
  14. 携程Java后台开发面经
  15. Android中如何利用Minui显示字符的最简单Demo
  16. 直击GITC2018 尚德机构苏万松:从消费互联网到产业互联网
  17. 【双写迁移方案】实现动态切换实现分库分表
  18. webpack.base.conf.js文件
  19. 【国家电网】2021年国家电网有限公司招聘高校毕业生公告
  20. Spring(Spring的理解+DI+Spring的创建)

热门文章

  1. 秒杀系统设计思路和实现方法
  2. 考计算机初级难不难,初级程序员好考吗_考试难不难_上学吧
  3. 电脑程序员需要考证件吗
  4. digester解析rule详解
  5. PR短视频特效转场 快速画面分割视频转场过渡PR转场模板
  6. 3DMAX安装包+安装教程
  7. 14 款(移动端)UI 框架
  8. dwg转换pdf方法
  9. Unity 实现人物移动
  10. 解决:The POM for xxx is missing, no dependency information available