HTML5带有
File API spec,它允许您创建允许用户在本地与文件交互的应用程序;这意味着您可以加载文件并在浏览器中呈现它们,而不需要实际上传文件。 File API的一部分是
FileReader接口,它使Web应用程序异步读取文件的内容。
这里有一个快速示例,使用FileReader类将图像读取为DataURL,并通过将图像标记的src属性设置为数据网址来呈现缩略图:
html代码:
JavaScript代码:
document.getElementById("files").onchange = function () {
var reader = new FileReader();
reader.onload = function (e) {
// get loaded data and render thumbnail.
document.getElementById("image").src = e.target.result;
};
// read the image file as a data URL.
reader.readAsDataURL(this.files[0]);
};
下面的HTML示例中的代码段会过滤掉用户选择的图片,并将所选文件呈现为多个缩略图预览:
function handleFileSelect(evt) {
var files = evt.target.files;
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML =
[
''
].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);