DiigIT | IT Community
No Profile Image
Welcome Guest
New User? Register | Login

Upload File in PhP using Ajax

By: rekha singh | 20 May 2010 5:59 pm

Hi All,

I'm up to 99% done with the below requirement.

 
I've created a PhP page(Main) which will list records and a link to change their "thumbnail". Clicking on it will open a "pop-up"
whichwill present a "File input" box and when user select a file to upload,this popup-page will send the form fields to a "process page" using AJAX. This Process page will upload the file and on success returns nothing else the error to the Ajax object in Popup. On return, the popup page will just reload the thumbnail on main page if success and closes itself.
 
I'm sure I've described what I wanted to do. Again, in brief:
Main->(Opens Popup)->Popup- >(Send file using AJAX)->Process
Process->(Upload File & return result to)->Popup-> (Reload img on Main
and closes itself)->Main
Below are my codes:
 
##### Main.php#### ##
'Sending only the part where Popup gets open
var poststr="imgType= "+imgType+ "&recId=" +recID+"& imgId="+imgID;
var url="popup.php? "+poststr;
window.open( url,'Upload
image','width= 360,height= 90,location= no,status= no');
 
#####PopUp.php# ####
<script>
function check_upload( myForm)
{
var upName;
if(myForm.imgType. value=="thumb" )
{
upName="mov_ thumb";
}
else
{
upName="mov_ img";
}
 
var imgName=myForm. elements[ upName].value;
var imgID='rec_' +myForm.imgId. value+'_thumb' ;
 
var formFeilds=Sarissa. formToQueryStrin g(myForm) ;
var xmlhttp = new XMLHttpRequest( );
xmlhttp.open( 'POST', 'process.php' , true);
 
/* The callback function */
xmlhttp.onreadystat echange = function()
{
if (xmlhttp.readyState == 4)
{
if (xmlhttp.status == 200)
{
var text = xmlhttp.responseTex t;
/*if(text != "") //if error
{
document.getElement ById('result' ).innerHTML = text;
}
else
{ // file uploaded well. Reload thumbnail
 
window.opener. document. getElementById( imgID).src= '../trailers/ '+imgName;
}*/ // if error check ends
 
} // if status check ends
} // if readystate check ends
} // The callback function ends
 
xmlhttp.setRequestH eader("Content- type", "multipart/form- data");
xmlhttp.setRequestH eader("Content- length", formFeilds.length) ;
xmlhttp.setRequestH eader("Connectio n", "close");
xmlhttp.send( formFeilds) ;
return false;
}
</script>
 
<FORM name="upload" onSubmit="return check_upload( this);">
<input type="hidden" name="submitted" value="true" >
<input type="hidden" name="action" value="upload" >
<input type="hidden" name="recId" value="<?php echo
$_GET['recId' ]?>">
<input type="hidden" name="imgId" value="<?php echo
$_GET['imgId' ]?>">
<input type="hidden" name="imgType" value="<?php echo
$_GET['imgType' ]?>" />
<input type="file" name="mov_thumb" class="fileUpld" />
<input type="submit" name="sbForm" value="Upload" class="submit" />
</FORM>
<div id="result" style="padding: 10px; color: #ff0000;"
class="movie- synop"></ div>
 
####Process. php#####
//BELOW 2 FORM VAR WILL COME FROM PopUp.php
$upType = ($_POST['imgType' ] == "thumb") ? "mov_thumb" : "mov_main";
$path = ($_POST['imgType' ] == "thumb") ? "../thumbnail/ " :
"../big_img/ ";
 
//$thumb_name will hold the upload file name without extension
 
//calling the function
$msg=upload_ img($upType, $thumb_name, $path);
 
function upload_img($ fileName, &$thumbName, $path)
{
$err=""; $maxSize=0;
$maxSize = ($fileName == "mov_thumb") ? 22000 : 81000;
if($_FILES[$ fileName] ['size'] <= 0)
{
$err="Please select a file to upload.";
return $err;
}
if($_FILES[$ fileName] ['size'] > $maxSize)
{
$err="File size should not be more than " . ceil($maxSize /
1024) . " kb.";
return $err;
}
 
$allowed_filetypes = array('jpg', 'jpeg');
if(!in_array( end(explode( ".", $_FILES[$fileName] ['name']) ),
$allowed_filetypes) )
{
$err="The file you attempted to upload is not allowed.";
return $err;
}
//CHECK TYPE: (what the browser sent)
if(($_FILES[ $fileName] ['type'] != "image/jpeg" ) &&
($_FILES[$fileName] ['type'] != "image/pjpeg" ))
{
$err="Uploaded file type un-recognized. ";
return $err;
}
//DOUBLE CHECK TYPE: if image MIME type from getimagesize( ) -In case
it was a FAKE!
$size = getimagesize( $_FILES[$ fileName] ['tmp_name' ]);
if(($size['mime' ] != "image/jpeg" ) && ($size['mime' ] !=
"image/pjpeg" ))
{
$err="Uploaded file type un-recognized. ";
return $err;
}
 
if(!is_writable( $path) || !is_dir($path) )
{
$err="The required directory either does not exist or is not
writable";
return $err;
}
 
$path=$path . basename( $_FILES[$fileName] ['name']) ;
if (file_exists( $path))
{
$err="A file with same name exist. Please rename your file and
try again.";
return $err;
}
 
if(!move_uploaded_ file($_FILES[ $fileName] ['tmp_name' ], $path))
{
$err="There was an error during the file upload. Please try
again.";
return $err;
}
$arrTemp=explode( ".", $_FILES[$fileName] ['name']) ;
$thumbName=$ arrTemp[0] ;
return $err;
}
 
Now the problem which I'm facing is, if I
use"xmlhttp. setRequestHeader ("Content- type", "multipart/form- data");"
thenthe error is "PHP Warning: Missing boundary in multipart/form- data
POSTdata in Unknown on line 0" and also the hidden form fields are
notgetting passed
 
But if I use
"xmlhttp.setRequest Header("Content- type","applicati on/x-www- form-urlenco\
ded");" then though the form fields arepassing but it throws me this
error "PHP Notice: Undefined index:mov_thumb in fileHandler. php on line
6". This line is"if($_FILES[ $fileName] ['size'] > $maxSize)"
In meaning, this would be if($_FILES[' mov_thumb' ]['size'] > $maxSize)
 
Can anyone help me in this coz I've search the net around 4 hours but found nothing. My all codes are working fine except this. I dont want to upload file through "sending binary data" as what I have got in search.
 
Please try to help me, its urgent.
 
Thanks & Regards to all,
 

Comments

No Comments Posted for this Article.

Leave a comment

Enter the text in the image
img
Can't read?
Type the characters you see in the picture below.


Close Move