Home > Article > Web Front-end > JavaScript preview image function to achieve refresh-free upload
This article introduces the use of JavaScript to implement a simple function of uploading preview images without refreshing.
This article uses two things, FormData and FileReader.
FileReader is used for image browsing.
FormData is used for ajax requests.
html code
First you need to create containers for forms and images.
<form enctype="multipart/form-data" id="oForm"> <input type="file" name="file" id="file" onchange="readAsDataURL()" /> <input type="button" value="提交" onclick="doUpload()" /> </form> <p> <img alt="" id="img"/> </p>
javascript code
##FormData:
function doUpload() { var formData = new FormData($( "#oForm" )[0]); console.log(formData); $.ajax({ url: 'pp', type: 'POST', data: formData, async: false, cache: false, contentType: false, processData: false, success: function (returndata) { console.log(returndata); }, error: function (returndata) { console.log(returndata); } }); }
FileReader:
function readAsDataURL(){ //检验是否为图像文件 var file = document.getElementById("file").files[0]; if(!/image\/\w+/.test(file.type)){ alert("看清楚,这个需要图片!"); return false; }else{ var reader = new FileReader(); //将文件以Data URL形式读入页面 reader.readAsDataURL(file); reader.onload=function(e){ var result=document.getElementById("img"); //显示文件 result.src= this.result ; } } }
The above is the detailed content of JavaScript preview image function to achieve refresh-free upload. For more information, please follow other related articles on the PHP Chinese website!