**js写本地文件**
最近在写系统相关任务配置的导入导出功能,其中导出功能设计的思路是将后台传来的json数组写到本地文件中,在网上找了相关代码,并做了一些相应的改进,最终的代码片段如下:
var fileName = "export.txt";
var jobConDataArray = JSON.stringify(data.jobConDataArray);
var type = "text/plain;charset=utf-8";
var blob;
if (typeof window.Blob == "function") {
blob = new Blob([jobConDataArray], {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;
var type = blob.type;
var force_saveable_type = 'application/octet-stream';
if (type && type != force_saveable_type) { // 强制下载,而非在浏览器中打开
var slice = blob.slice || blob.webkitSlice || blob.mozSlice;
blob = slice.call(blob, 0, blob.size, force_saveable_type);
}
var url = URL.createObjectURL(blob);
var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
save_link.href = url;
save_link.download = fileName;
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
save_link.dispatchEvent(event);
URL.revokeObjectURL(url);
JSON.stringify()将传来的json数组对象转换为字符窜,Blob对象的创建需要注意,因为Chrome浏览器无windows.BlobBuilder对象,这里需要特殊处理。var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');这行代码最好不要进行改动。
js 写本地文件
最新推荐文章于 2024-09-04 20:18:34 发布