I am trying to change profile image with the code below. It permits few formats and size less than 2mb, In case it's not so it will give error. Upload works well but something is wrong with errors, on choosing an image type that is not permitted by code or image is more than 2mb it neither uploads image nor shows error just progress bar completes its process but no image is changed or uploaded to database nor any error is shown, I want to have error when image is above 2mb or format not permitted by code.
imageupload.php
if ($_FILES['image_upload_file']["error"] > 0) {
$output['error']= "Error in File";
}
elseif (!in_array($_FILES['image_upload_file']["type"], $allowedImageType)) {
$output['error']= "You can only upload JPG, PNG and GIF file";
}
elseif (round($_FILES['image_upload_file']["size"] / 1024) > 4096) {
$output['error']= "You can upload file size up to 4 MB";
} else {
/*create directory with 777 permission if not exist - start*/
createDir(IMAGE_SMALL_DIR);
createDir(IMAGE_MEDIUM_DIR);
/*create directory with 777 permission if not exist - end*/
$path[0] = $_FILES['image_upload_file']['tmp_name'];
$file = pathinfo($_FILES['image_upload_file']['name']);
$fileType = $file["extension"];
$desiredExt='jpg';
$fileNameNew = rand(333, 999) . time() . ".$desiredExt";
$path[1] = IMAGE_MEDIUM_DIR . $fileNameNew;
$path[2] = IMAGE_SMALL_DIR . $fileNameNew;
if (createThumb($path[0], $path[1], $fileType, IMAGE_MEDIUM_SIZE, IMAGE_MEDIUM_SIZE,IMAGE_MEDIUM_SIZE)) {
if (createThumb($path[1], $path[2],"$desiredExt", IMAGE_SMALL_SIZE, IMAGE_SMALL_SIZE,IMAGE_SMALL_SIZE)) {
$output['status']=TRUE;
$output['image_medium']= $path[1];
$output['image_small']= $path[2];
}
}
}
echo json_encode($output);
}
?>
settings.php
<script>
$(document).on('change', '#image_upload_file', function () {
var progressBar = $('.progressBar'), bar = $('.progressBar .bar'), percent = $('.progressBar .percent');
$('#image_upload_form').ajaxForm({
beforeSend: function() {
progressBar.fadeIn();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
success: function(html, statusText, xhr, $form) {
obj = $.parseJSON(html);
if(obj.status){
var percentVal = '100%';
bar.width(percentVal)
percent.html(percentVal);
$("#imgArea>img").prop('src',obj.image_medium);
}else{
alert(obj.error);
}
},
complete: function(xhr) {
progressBar.fadeOut();
}
}).submit();
});
</script>
form
<form enctype="multipart/form-data" action="imageupload.php" method="post" name="image_upload_form" id="image_upload_form">
<div id="imgArea"><img src="<?php echo $profile_photo; ?>">
<div class="progressBar">
<div class="bar"></div>
<div class="percent">0%</div>
</div>
<div id="imgChange" style="background: url("../img/overlay.png") repeat scroll 0 0 rgba(0, 0, 0, 0);bottom: 0;color: #FFFFFF;display: block;height: 30px;left: 0;line-height: 32px;position: absolute;width: 100%;"><p>Click on photo to change</p>
<input type="file" accept="image/*" name="image_upload_file" id="image_upload_file">
</div>
</div>
</form>
Related
I have created a jQuery/AJAX script for file uploading and I handle the upload with PHP. It works perfectly with a progress bar and validations. There is one issue however, I cannot get any response text that I have set in PHP and encoded it using json_encode();, but don't get any response and get this instead:
<div class="upload-div">
<form method="post" enctype="multipart/form-data" class="upload_form" >
<label for="file" id="file_label" class="file-label"><i class="fa fa-plus"></i> إضافة صور<input type="file" name="files[]" id="file" multiple="" accept="image/*" /></label>
<input type="submit" id="upload_files" name="submitUpload" value="رفع الصور" />
</form>
<div class="progress">
<div class="bar"></div>
</div>
<div class="status-message"></div>
<div class="images-previews"></div>
<div id="next_step"></div>
<span class="submit-buttons">
<i class="fa fa-arrow-right"></i> الرجوع
<form method="post"><input type="submit" name="submitNoPics" value="التقدم بدون صورة" /></form>
</span>
</div>
<script src="js/upload.js"></script>
<script src="js/jquery.form.min.js"></script>
{"message":"Successfully uploaded 1 files!"}
As you can see the message I want to display is on the last line of code but it doesn't show alone. It shows with the whole HTML document. I will post my HTML and PHP code below, because I am new to Ajax and I am struggling. Please help me if you can and explain because I don't just want to get it done, I want to actually understand how and why this is not working. Thank you.
PHP:
<?php
//file upload
$extensions = array('jpeg', 'jpg', 'png', 'gif');
$dir = 'user-uploads/';
$count = 0;
$imgCounter = 1;
if ($_SERVER['REQUEST_METHOD'] == 'POST' and isset($_FILES['files'])){
for($x = 1; $x <= 8; $x++){
unlink('user-uploads/img'.$listingID.'-'.$x.'.jpg');
unlink('user-uploads/img'.$listingID.'-'.$x.'.png');
unlink('user-uploads/img'.$listingID.'-'.$x.'.gif');
}
mysqli_query($connectionDB, "DELETE FROM ad_image_tbl WHERE ad_id = $listingID");
// loop all files
foreach ( $_FILES['files']['name'] as $i => $name ){
// if file not uploaded then skip it
if ( !is_uploaded_file($_FILES['files']['tmp_name'][$i]) )
continue;
/* skip unprotected files
if( !in_array(pathinfo($name, PATHINFO_EXTENSION), $extensions) )
continue;
*/
switch($_FILES['files']['type'][$i]){
case 'image/jpeg' : $ext = '.jpg'; break;
case 'image/png' : $ext = '.png'; break;
case 'image/gif' : $ext = '.gif'; break;
default : $ext = '';
}
if($ext == ''){
echo errorMessage('<li>الملف المرفق لا يعتبر صورة</li>');
$error_message = 'الملف المرفق لا يعتبر صورة';
$message = array('message'=>'Attached file is not a valid image file.');
exit();
}
else{
// now we can move uploaded files
if($count <= 7 ){
$listingImage = $dir.'img'.$listingID.'-'.$imgCounter.$ext;
if( move_uploaded_file($_FILES["files"]["tmp_name"][$i], $listingImage))
mysqli_query($connectionDB, "INSERT INTO ad_image_tbl VALUES('$imgCounter', '$listingID', '$listingImage')");
$imgCounter++;
$count++;
}
}
}
$message = array('message'=>'Successfully uploaded '.$count.' files!');
echo json_encode($message);
}
?>
jQuery/AJAX:
$(function() {
/* variables */
var fileInput = document.getElementById('file');
var fileCount = fileInput.files.length;
if(fileCount > 8){
fileCount = 8;
}
var bar = $('.bar');
var progress = $('.progress');
/* submit form with ajax request using jQuery.form plugin */
$('.upload_form').ajaxForm({
/* set data type json */
dataType:'JSON',
/* reset before submitting */
beforeSend: function() {
bar.width('0%');
progress.css('display', 'block');
},
/* progress bar call back*/
uploadProgress: function(event, position, total, percentComplete) {
var pVel = percentComplete + '%';
bar.width(pVel);
},
/* complete call back */
complete: function(message){
// var responseMessage = $.parseJSON(data.responseText);
progress.css('display', 'none');
document.getElementById('next_step').innerHTML = '<form method="post"><input type="submit" name="uploadSubmit" value="الانتهاء" /></form>';
console.log(message)
}
});
});
Why could you use a plugin to handle upload.
dropzone.js
You can get response as below
$(function() {
Dropzone.options.uiDZResume = {
success: function(file, response){
alert(response);
}
};
});
I am trying to create an upload progressbar when a file is being uploaded.
This is my part of php:
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
$root = '/users/'.$UserName.'/';
if (!is_dir($root))
{
#mkdir('users/'.$UserName, 0777);
if (($_FILES["file"]["size"] < $MaxUploadSize) && in_array($extension, $allowedExts))
{
echo 'upload successful';
$data = explode(".",$_FILES["file"]["name"]);
$newfilename = $realname;
move_uploaded_file($_FILES["file"]["tmp_name"], 'users/'.$UserName.'/' . $newfilename);
}
else
{
echo '<span class="failed">Upload failed!</span>';
}
}
} // endif SERVER REQUEST
For the progression bar, i use this javascript:
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('#sfmform').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
success: function() {
var percentVal = '100%';
bar.width(percentVal)
percent.html(percentVal);
},
});
In combination with: http://malsup.github.com/jquery.form.js
My form looks like this:
<form id="sfmform" action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" multiple"" />
<br />
<input type="submit" class="Button Primary" name="submit" value="Upload">
<br /><br />
</form>
The progressbar works fine, but the php echo's are not being displayed, whether they are successful or when failed. Without the js, the echos work fine!
what i am doing wrong?
I think you have to receive response in your success call-back:
success: function(data) {
alert(data);
var percentVal = '100%';
bar.width(percentVal)
percent.html(percentVal);
}
Use a variable to check whether the upload was successful and then check that value inside the body of the html
PHP
$check=0;
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
//php code
if (($_FILES["file"]["size"] < $MaxUploadSize) && in_array($extension, $allowedExts))
{
$check=1;
}
}
HTML
<html>
<body>
<!-- place your form -->
<?php if ($check==1)
{
echo "Upload Successful";
}
?>
</body>
</html>
I have little problem.
this is my html
<div class="row" style="margin-bottom: 10px;">
<div class="col-xs-1">
<span class="upload-excell btn btn-success" id="uploadExcellBtn"><i class="fa fa-upload"></i> Import Excel</span>
<div class="progress hidden" id="progress">
<div id="progressbat" class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="min-width: 2em; width: 0;">
0%
</div>
</div>
</div>
<div class="col-xs-4">
<input class="form-control filter" type="search" title="filter" placeholder="Search...">
</div>
<div class="col-xs-7"></div>
</div>
<form class="Upload-form hiddenfile" method="post" enctype="multipart/form-data" action='upload url'>
<input type="hidden" name="csrf_token" value="<?php echo $this->session->csrf_token; ?>" />
<input type="file" name="file" class="excel-file"/>
</form>
this is my ajax
var $PROGRESS_BAR = document.getElementById('progressbat'),
progres = document.getElementById('progress');
$(document).on('submit', '.Upload-form', function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded / evt.total * 100);
$PROGRESS_BAR.style.width = percentComplete + '%';
$PROGRESS_BAR.innerHTML = percentComplete + '%';
}
}, false);
return xhr;
},
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
beforeSend: function(){
uploadExcellBtn.className = "upload-excell btn btn-success hidden";
progres.className = "progress";
$PROGRESS_BAR.style.width = '0%';
$PROGRESS_BAR.innerHTML = '0%';
},
success:function(){
$PROGRESS_BAR.style.width = '0%';
$PROGRESS_BAR.innerHTML = '0%';
$PROGRESS_BAR.className = "progress-bar progress-bar-success";
},
complete: function () {
var xhr2 = new XMLHttpRequest();
xhr2.open("GET", "new url", true);
xhr2.onerror = function() { console.log('[XHR] Fatal Error.'); };
xhr2.onreadystatechange = function() {
if (xhr2.readyState > 2){
var responseInfo = xhr2.responseText.replace(/}/g, '}/').split("/").clean(undefined);
for(var $i = 0; $i < responseInfo.length; $i++){
var parsedinfo = JSON.parse(responseInfo[$i]),
load = parseInt(parsedinfo.loaded);
if(load > loaded){
loaded = load;
percentage = Math.round(load / parseInt(parsedinfo.total) * 100);
$PROGRESS_BAR.style.width = percentage + '%';
$PROGRESS_BAR.innerHTML = percentage + '%';
}
}
}
if (xhr2.readyState == 4){
percentage = 0;
$PROGRESS_BAR.style.width = '0%';
$PROGRESS_BAR.innerHTML = '0%';
$PROGRESS_BAR.className = "progress-bar progress-bar-danger";
progres.className = "progress hidden";
uploadExcellBtn.className = "upload-excell btn btn-success";
refresh();
}
};
xhr2.send();
},
error: function(data){
console.log("error");
console.log(data);
}
});
return false;
});
I think it is possible to clean this code... as you understand in the first I have file upload and after complete I need to send request for reading this file it is reading on server side very well but I can not response my progress bar after upload complete.
this is my php function for uploading file
$excell = $_FILES["file"]["name"];
$uploadedfile = $_FILES['file']['tmp_name'];
if ($excell) {
$filename = stripslashes($_FILES['file']['name']);
$extension = $this->getExtension($filename);
$extension = strtolower($extension);
if ($extension == ("xlsx" || "xls")) {
$newname = $this->Conf->root_dir."/uploads/".Generate::string(5).".$extension";
$this->Session->new_file = $newname;
move_uploaded_file($uploadedfile, $newname);
echo true;
} else {
echo ' It is not Excell ';
}
} else {
echo ' error on upload ';
}
and this code is for reading
set_time_limit(0);
ob_implicit_flush(true);
ob_end_flush();
$xlsx = #(new SimpleXLSX($this->Session->new_file));
$data = $xlsx->rows();
$totalitems = count($data);
$lastkey = $totalitems - 1;
$current = 0;
foreach ($data as $key => $val) {
$current++;
if ($key == 0 || $key == $lastkey) continue;
// here I`m inserting in tho database
sleep(1);
$response = array(
'loaded' => $current,
'total' => $totalitems
);
echo json_encode($response);
}
sleep(1);
unlink($this->Session->new_file);
unset($this->Session->new_file);
$response = array(
'loaded' => $totalitems,
'total' => $totalitems
);
echo json_encode($response);
response for upload is working very well
but reading response not working...
I resolved this problem with jquery ajax..
with xhr parameter...
I have an ajax upload script which i will post below. It will upload any file with any extention. I want it to only upload .png files but i dont know how to do that.
Here are my files:
<h1>Ajax File Upload Demo</h1>
<form id="myForm" action="upload.php" method="post" enctype="multipart/form-data">
Name it:
<input type="text" name="upload_name">
<br>
<input type="file" size="60" name="myfile">
<input type="submit" value="Ajax File Upload">
</form>
<div id="progress">
<div id="bar"></div>
<div id="percent">0%</div >
</div>
<br/>
<div id="message"></div>
<script>
$(document).ready(function()
{
var options = {
beforeSend: function()
{
$("#progress").show();
//clear everything
$("#bar").width('0%');
$("#message").html("");
$("#percent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete)
{
$("#bar").width(percentComplete+'%');
$("#percent").html(percentComplete+'%');
},
success: function()
{
$("#bar").width('100%');
$("#percent").html('100%');
},
complete: function(response)
{
$("#message").html("<font color='green'>"+response.responseText+"</font>");
},
error: function()
{
$("#message").html("<font color='red'> ERROR: unable to upload files</font>");
}
};
$("#myForm").ajaxForm(options);
});
</script>
PHP:
<?php
$upload_name = $_POST['upload_name'];
$idx = strpos($_FILES['myfile']['name'],'.');
$ext = substr($_FILES['myfile']['name'],$idx);
$file_name = $upload_name . $ext;
$output_dir = "uploads/";
if(isset($_FILES["myfile"]))
{
//Filter the file types , if you want.
if ($_FILES["myfile"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
//move the uploaded file to uploads folder;
// move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $_FILES["myfile"]["name"]);
// echo "Uploaded File :".$_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$file_name);
echo "Uploaded File :" . $file_name;
}
}
?>
Sorry, i'm new and code blocks wont work for me. If someone could update, that would be great.
Client side
change your input file field this only works for modern browsers IE10+
Google Chrome 8.0+ and Firefox 4.0+
<input type="file" size="60" name="myfile" accept="image/png" />
PHP
$ext = pathinfo( $file_name , PATHINFO_EXTENSION );
if(strtolower($ext) == 'png' && $_FILES["file"]['type'] == "image/png")
{
// upload file
} else{
// not allowed
}
You can check file extension or mime type at server side.
// check extension
$info = new SplFileInfo($_FILES['myfile']['name']);
if ($info->getExtension() !== 'png') {
// return error
}
// or check file mime type
if (mime_content_type($_FILES['myfile']['name']) !== 'image/png') {
// return error
}
Example php:
$output_dir = "uploads/";
$upload_name = $_POST['upload_name'];
if(isset($_FILES["myfile"])) {
// Check upload errors
if ($_FILES["myfile"]["error"] > 0) {
echo "Error: " . $_FILES["file"]["error"] . "<br>";
return;
}
// Check extensions
$info = new SplFileInfo($_FILES['myfile']['name']);
if ($info->getExtension() !== 'png') {
echo "Error: Only .png files are allowed";
return;
}
// Upload file
$file_name = $upload_name . $info->getExtension();
move_uploaded_file($_FILES["myfile"]["tmp_name"], $output_dir . $file_name);
echo "Uploaded File :" . $file_name;
}
I've html form. Now i'm trying to upload file using php with ajax request. But I'm getting following error message when I upload the file by php with ajax request. is it my ajax request problem or anything ?
Notice: Undefined index: file in D:\Software Installed\xampp\htdocs\wix\users\insert_galary.php on line 16
html form:
<p>Add more</p>
<div id="dialog-modal2" title="Upload your galary image" style="display: none;">
<form method="post" action="insert_galary.php" id="myForm2" enctype="multipart/form-data" >
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>Upload image</td>
<td><input type="file" name="file" class="tr"/></td>
</tr>
</table>
</form>
<span id="result2"></span>
<script type="text/javascript">
$("#sub2").click( function() {
$.post( $("#myForm2").attr("action"),
$("#myForm2 :input").serializeArray(),
function(info){ $("#result2").html(info);
});
clearInput();
});
$("#myForm2").submit( function() {
return false;
});
</script>
</div>
function showDialog2()
{
$("#dialog-modal2").dialog(
{
width: 610,
height: 350,
open: function(event, ui)
{
var textarea = $('<textarea style="height: 276px;">');
$(textarea).redactor({
focus: true,
autoresize: false,
initCallback: function()
{
this.set('<p>Lorem...</p>');
}
});
}
});
}
Php form:
$gid = mt_rand(100000, 999999);
$file = $_FILES["file"]["name"];
$type = $_FILES["file"]["type"];
$size = ($_FILES["file"]["size"] / 1024);
$temp = $_FILES["file"]["tmp_name"];
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
$galary_pic = $gid.".".$extension;
$galary_directory = "../galary_images/";
$err = array();
if(isset($file))
{
if(empty($file))
$err[] = "Upload your picture";
elseif(!in_array($extension, $allowedExts))
$err[] = "Uploaded file must be gif, jpeg, jpg, png format";
elseif($size > 500)
$err[] = "Uploaded file must be within 500kb";
}
if(!empty($err))
{
echo "<div class='error'>";
foreach($err as $er)
{
echo "<font color=red>$er.</font><br/>";
}
echo "</div>";
echo "<br/>";
}
else
{
echo "sql query";
}
Note: I already submit this question last day but I can't get any proper answer. Sorry about it
You're not uploading a file but just making a POST request without any file attached. If you're looking for an ajax file uploader, try jquery file upload here
http://blueimp.github.io/jQuery-File-Upload