栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

上传前显示图片预览

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

上传前显示图片预览

HTML5带有FileAPI规范,它使您可以创建应用程序,使用户可以在本地与文件交互;这意味着您可以加载文件并在浏览器中呈现它们,而无需实际上传文件。FileAPI的一部分是FileReader接口,它使Web应用程序可以异步读取文件的内容。

这是一个简单的示例,该示例利用

FileReader
该类将图像读取为DataURL并通过将
src
image标签的属性设置为数据URL来呈现缩略图:

html代码:

<input type="file" id="files" /><img id="image" />

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 =          [ '<img  src="', e.target.result, '" title="', escape(theFile.name), '"/>'          ].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);<input type="file" id="files" multiple /><output id="list"></output>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/464884.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号