Javascript文件加载:LABjs和RequireJS
- Pstrey - 阮一峰的网络日志传统上,加载Javascript文件都是使用
--><input type="file" id="file" onchange="handleFiles(this.files)"/>
当选择了一个文件时,就会把包含这个文件的列表(一个FileList对象)作为参数传给handleFiles()函数了。function handleFiles(files) {
if (files.length) {
var file = files[0];
var reader = new FileReader();
if (/text\/\w+/.test(file.type)) {
reader.onload = function() {
$('<pre>' + this.result + '</pre>').appendTo('body');
}
reader.readAsText(file);
}
}
}
这里的this.result实际上就是reader.result,也就是读取出来的文件内容。function handleFiles(files) {
if (files.length) {
var file = files[0];
var reader = new FileReader();
if (/text\/\w+/.test(file.type)) {
reader.onload = function() {
$('<pre>' + this.result + '</pre>').appendTo('body');
}
reader.readAsText(file);
} else if(/image\/\w+/.test(file.type)) {
reader.onload = function() {
$('<img src="' + this.result + '"/>').appendTo('body');
}
reader.readAsDataURL(file);
}
}
}
<input type="file" id="files" multiple="" onchange="handleFiles(this.files)"/>
这样handleFiles()里就需要遍历处理files了。var BlobBuilder = BlobBuilder || WebKitBlobBuilder || MozBlobBuilder;
var URL = URL || webkitURL || window;
function saveAs(blob, filename) {
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);
}
var bb = new BlobBuilder;
bb.append('Hello, world!');
saveAs(bb.getBlob('text/plain;charset=utf-8'), 'hello world.txt');
测试时会提示保存一个文本文件。Chrome需要把网页放在服务器上或插件里。