Home >Web Front-end >JS Tutorial >Tutorial on how to use JavaScript to preview and upload images without refreshing the page
This article mainly introduces in detail the JavaScript function of uploading preview images without refreshing. It has certain reference value. Interested friends can refer to
How to implement the function of uploading without refreshing? Handwritten non-refresh upload requires two things, FormData and FileReader.
FileReader is used for image browsing.
FormData is used for ajax requests.
html code
First create a container for the form and image
##
<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 Tutorial on how to use JavaScript to preview and upload images without refreshing the page. For more information, please follow other related articles on the PHP Chinese website!