为了账号安全,请及时绑定邮箱和手机立即绑定

上传前显示图像预览

上传前显示图像预览

素胚勾勒不出你 2019-07-16 18:19:43
上传前显示图像预览在我的HTML表单中,我使用类型文件进行输入,例如: <input type="file" multiple>然后单击输入按钮选择多个文件。现在我想在提交表单之前显示选定图像的预览。如何在HTML 5中做到这一点?
查看完整描述

3 回答

?
慕容3067478

TA贡献1773条经验 获得超3个赞

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

下面是一个使用FileReader类将图像读取为DataURL,并通过设置src图像标记到数据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]);};

这是一篇关于在JavaScript中使用文件API.

下面的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 style="height: 75px; border: 1px solid #000; margin: 5px" 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>


查看完整回答
反对 回复 2019-07-16
  • 3 回答
  • 0 关注
  • 379 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信