您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

上传前显示图片预览

上传前显示图片预览

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

这是一个简单的示例,该示例利用FileReader该类将图像读取为DataURL并通过将srcimage标签属性设置为数据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 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>
其他 2022/1/1 18:13:38 有505人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶