I\'m trying to use jquery and PHP to upload an image like so:
HTML
Tested and working on Goolge Chrome, Opera, Firefox, Safari.
doesn't work with IE8 or lower
Create a FormData object and append the file with index photo-img and POST it to your server with the help of XMLHttpRequest
$(function() {
$('#photo-img').change(function(){
var file = this.files[0];
// do your validation here
var formData = new FormData();
formData.append( 'photo-img', file ); // append the file to form data
var xhr = false;
if ( typeof XMLHttpRequest !== 'undefined' ) {
xhr = new XMLHttpRequest();
}
else {
var versions = [ "MSXML2.XmlHttp.5.0", "MSXML2.XmlHttp.4.0", "MSXML2.XmlHttp.3.0", "MSXML2.XmlHttp.2.0", "Microsoft.XmlHttp" ];
for( var i = 0, len = versions.length; i < len; i++ ) {
try {
xhr = new ActiveXObject( versions[i] );
break;
}
catch(e) {}
}
}
if ( xhr ) {
// replace test.php with your own upload script url
xhr.open( "POST", "test.php", true );
xhr.onreadystatechange = function() {
if ( this.readyState === 4 && this.status == 200 ) {
var response = this.response || this.responseText;
/** Do Something with the reponse **/
response = $.parseJSON( response );
if ( response && response.message ) {
window.alert( response.message );
}
}
}
// now send the formData to server
xhr.send( formData );
}
});
});
A better image upload handling on server side and return a JSON object as response
upload_max_filesize directive in php.ini';
break;
case UPLOAD_ERR_FORM_SIZE:
$error = 'Error '.$code.': The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
break;
case UPLOAD_ERR_PARTIAL:
$error = 'Error '.$code.': The uploaded file was only partially uploaded';
break;
case UPLOAD_ERR_NO_FILE:
$error = 'Error '.$code.': No file was uploaded';
break;
case UPLOAD_ERR_NO_TMP_DIR:
$error = 'Error '.$code.': Missing a temporary folder';
break;
case UPLOAD_ERR_CANT_WRITE:
$error = 'Error '.$code.': Failed to write file to disk';
break;
case UPLOAD_ERR_EXTENSION:
$error = 'Error '.$code.': A PHP extension stopped the file upload';
break;
default:
$error = 'Error '.$code.': Unknown upload error';
break;
}
}
else {
$iminfo = @getimagesize( $image["tmp_name"] );
if ( $iminfo && is_array( $iminfo ) ) {
if ( isset( $iminfo[2] ) && in_array( $iminfo[2], $valid ) && is_readable( $image["tmp_name"] ) ) {
if ( !move_uploaded_file( $image["tmp_name"], $target ) ) {
$error = "Error while moving uploaded file";
}
}
else {
$error = "Invalid format or image is not readable";
}
}
else {
$error = "Only image files are allowed (jpg, gif, png)";
}
}
if ( empty( $error ) ) {
echo json_encode( array( "error" => 0, "message" => "Upload success!" ) );
}
else {
echo json_encode( array( "error" => 1, "message" => $error ) );
}
exit();
}
?>