Home >Web Front-end >JS Tutorial >FileReader in JS implements image upload preview
This time I will bring you the preview of image upload using FileReader in JS. What are the precautions for implementing image upload preview using FileReader in JS? The following is a practical case, let’s take a look.
FileReader is part of the HTML5 File API. It implements an asynchronous file reading mechanism. You can think of FileReader as XMLHttpRequest, the only difference is that it reads thefile system instead of the remote server. In order to read the data in the file, FileReader provides the following methods.
<p id="wrapper"> <input id="fileUpload" type="file" multiple /><br /> <p id="image-holder"> </p> </p>
$("#fileUpload").on('change', function () { //获取上传文件的数量 var countFiles = $(this)[0].files.length; var imgPath = $(this)[0].value; var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase(); var image_holder = $("#image-holder"); image_holder.empty(); if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") { if (typeof (FileReader) != "undefined") { // 循环所有要上传的图片 for (var i = 0; i < countFiles; i++) { var reader = new FileReader(); reader.onload = function (e) { $("<img />", { "src": e.target.result, "class": "thumb-image" }).appendTo(image_holder); } image_holder.show(); reader.readAsDataURL($(this)[0].files[i]); } } else { alert("你的浏览器不支持FileReader!"); } } else { alert("请选择图像文件。"); } });
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
How to implement the decorator pattern in node.jsDetailed steps for using Django multiple databasesThe above is the detailed content of FileReader in JS implements image upload preview. For more information, please follow other related articles on the PHP Chinese website!