Você está na página 1de 3

HowToUploadImageUsingPHPAndJQuery

PostedinJavaScript,PHPBystepbloggerOnMay5,2015
ThereislotsofgreatimageuploaderontheWorldWideWeb,buttheyarecomplicatedtoimplementwithoutany
helpanditstimeconsuming,ifyouarebeginner.
Herewearegoingtoexplainhowtocreateanajaxbasedimageuploader,whichmeansuploadimagewithout
loadingthebrowser.ItsverysimpleandachievedbyfewlinesofPHPandjQuerycode.
Inthegivenexample,imagepreviewedbeforeuploadingonserverandonceuserwillhitonsubmitbuttonitwill
storeonserveratspecificlocation.
index.html
<html>
<head>
<title>AjaxImageUploadUsingPHPandjQuery</title>
<linkrel="stylesheet"href="styles.css"/>
<scriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(e){
$("#uploadAjaxImage").on('submit',(function(e){
e.preventDefault();
$("#message").empty();
$('#loading').show();
$.ajax({
url:"ajax_upload_file.php",//Urltowhichtherequestissend
type:"POST",//Typeofrequesttobesend,calledasmethod
data:newFormData(this),//Datasenttoserver,asetofkey/valuepairs(i.e.formfieldsandvalues)
contentType:false,//Thecontenttypeusedwhensendingdatatotheserver.
cache:false,//Tounablerequestpagestobecached
processData:false,//TosendDOMDocumentornonprocesseddatafileitissettofalse
success:function(data)//Afunctiontobecalledifrequestsucceeds
{
$('#loading').hide();
$("#message").html(data);
}
});
}));

//Functiontopreviewimageaftervalidation
$(function(){
$("#file").change(function(){
$("#message").empty();//Toremovethepreviouserrormessage
varfile=this.files[0];
varimagefile=file.type;
varmatch=["image/jpeg","image/png","image/jpg"];
if(!((imagefile==match[0])||(imagefile==match[1])||(imagefile==match[2])))
{
$('#previewing').attr('src','noimage.png');
$("#message").html("<pid='error'>PleaseSelectAvalidImageFile</p>"+"<h4>Note</h4>"+"<span
id='error_message'>Onlyjpeg,jpgandpngImagestypeallowed</span>");
returnfalse;
}else{
varreader=newFileReader();

reader.onload=imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
});
functionimageIsLoaded(e){
$("#file").css("color","#FFFFFF");
$('#image_preview').css("display","block");
$('#previewing').attr('src',e.target.result);
$('#previewing').attr('width','250px');
$('#previewing').attr('height','230px');
};
});
</script>
</head>
<body>
<divclass="main">
<formid="uploadAjaxImage"action=""method="post"enctype="multipart/formdata">
<divid="image_preview"><imgid="previewing"src="noimage.jpg"width="250"height="230"/></div>
<divid="selectImage">
<label>SelectYourImage</label><br/>
<inputtype="file"name="file"id="file"required/>
<inputtype="submit"value="Upload"class="submit"/>
</div>
</form>
</div>
<spanid='loading'><imgsrc="ajaxloader.gif"/></span>
<divid="message"></div>
</body>
</html>

ajax_upload_file.php
<?php
if(isset($_FILES["file"]["type"]))
{
$allowedExtension=array("jpeg","jpg","png");
$fileExtension=pathinfo($_FILES["file"]["name"],PATHINFO_EXTENSION);
if(in_array($fileExtension,$allowedExtension)){
if($_FILES["file"]["size"]<1000000){//Approx.1000kbfilescanbeuploaded.
if($_FILES["file"]["error"]>0){
echo"ReturnCode:".$_FILES["file"]["error"]."<br/><br/>";
}else{
if(file_exists("upload/".$_FILES["file"]["name"])){
echo$_FILES["file"]["name"]."<spanid='invalid'><b>alreadyexists.</b></span>";
}else{
$sourcePath=$_FILES['file']['tmp_name'];//Storingsourcepathofthefileinavariable
$targetPath="upload/".$_FILES['file']['name'];//Targetpathwherefileistobestored
move_uploaded_file($sourcePath,$targetPath);//MovingUploadedfile
echo"<spanid='success'>ImageUploadedSuccessfully...!!</span><br/>";
echo"<br/><b>FileName:</b>".$_FILES["file"]["name"]."<br>";
echo"<b>Type:</b>".$_FILES["file"]["type"]."<br>";
echo"<b>Size:</b>".($_FILES["file"]["size"]/1024)."kB<br>";
echo"<b>Tempfile:</b>".$_FILES["file"]["tmp_name"]."<br>";
}
}
}else{

echo"<spanid='invalid'>***Filesizeisgreaterthan1000Kb***<span>";
}
}else{
echo"<spanid='invalid'>***InvalidfileType***<span>";
}
}
?>

Você também pode gostar