利用浏览器做一个工具时,往往操作的对象就是文件本身,我们需要打开文件,然后对文件进行处理,最后,将处理后的数据,以文件的形式保存起来
那么:我们怎么保存文件呢?
以下提供两个方案 :
1 大家都不陌生,我们在浏览器上经常使用,单击一个链接,启动下载,如下:
function createDownloadLink(dataUrl,fileName){
var save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a");
save_link.download = fileName;
save_link.href = dataUrl;
}
function click = function(node) {
var event = doc.createEvent("MouseEvents");
event.initMouseEvent(
"click", true, false, view, 0, 0, 0, 0, 0
, false, false, false, false, 0, null
);
node.dispatchEvent(event);
}
var dataUrl = "data:xxxxxxxxxxxxxxxxxxxxxxx";//资源的dataUrl
var saveLink = createDownLoadLink(dataUrl);
click(saveLink);
原理是创建一个下载的链接,将连接的href 用dataUrl赋值。然后触发链接的点击事件,实现下载。
2 利用html5 进行保存文件操作
关键步骤:
var req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem ;
req_fs(window.TEMPORARY, 5*1024*1024,createAndSaveFile);
function createAndSaveFile(fs){
fs.root.getFile('log.txt', {create: true}, function(fileEntry) {
// Create a FileWriter object for our FileEntry (log.txt).
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
console.log('Write completed.');
};
fileWriter.onerror = function(e) {
console.log('Write failed: ' + e.toString());
};
// Create a new Blob and write it to log.txt.
var bb = new BlobBuilder(); // Note: window.WebKitBlobBuilder in Chrome 12.
bb.append('Lorem Ipsum');
fileWriter.write(bb.getBlob('text/plain'));
}, errorHandler);
}, errorHandler);
}
参考:
https://github.com/eligrey/FileSaver.js/
http://www.html5rocks.com/zh/tutorials/file/filesystem/ 重点
http://stackoverflow.com/questions/13130070/html5-filesystems-api-letting-users-save-files-to-their-actual-filesystem
http://www.html5rocks.com/zh/tutorials/file/filesystem/
http://www.xyhtml5.com/read-and-save-files-using-javascript.html