Ajax file Upload giving the undefined index file from the php side - php

I've tried everything i came across and i am sure there is something i dont have in the code .Please i need some help thks.
This is the html which is a form with one input which should receive the file
<div id="Posts">
<h1 style="text-align: center;color: red;">SERVICES</h1>
<p style="text-align: center;"><span style="color:red;">***</span> please ensure to look at the definitions of every field... <span style="color:red;">***</span></p>
<form id="promo_imgs" enctype="multipart/formdata">
<h5 style="text-align: center;"> About the Services You offer</h5><hr style="width: 30%; border:0.5px dashed red;">
<div id="imgpr" class="imgpromo" style="max-width: 40%; min-height: 60px;border:dashed 0.5px;">
<label for="promotion" class="btn btn-primary">
Select an Image
</label>
<img src="" alt="" width="100%" style="max-height: 250px;" id="img">
<input type="file" name="promo0" accept=".png, .jpeg, .jpg" id="promotion" style="display:none;">
</div>
<button class="btn btn-primary" type="submit" id="serv_upload" name="serv_upload">Upload</button>
</form><span id="ajax">
<!--upload an image -->
</span>
then this is the jquery part of it which should preview the image (which works) and then upload the image(which goes successfully to return an undefined index file error)
/* to preview before upload service images*/
$(document).on('change',"#promotion",function(){
var link =URL.createObjectURL(event.target.files[0]);
console.log(link);
var $this=$(this);
$("#img").slideDown("fast").attr('src',link);
$("#serv_upload").slideDown("slow");
});
/* to upload service images*/
$(document).on('click',"#serv_upload",function(e){
e.preventDefault();
$("#ajax").html("Uploading...");
var files = $('#promotion').val(e.target.files);
for (var i = 0; i < files.length; i++) {
var file = files[i];
var formdata= new FormData();
formdata.append('file',file);
$("#ajax").append(file.name);
$.ajax({
type:"POST",
url:"aboutinsert.php",
data:{formdata:formdata},
processData:false,
contentType:false,
cache:false,
success: function(data){
$("#ajax").html(data);
}
});
}
});
Finally the php part
$dir="img/portfolio" ;
$file = $_FILES['file']['name'];
$path = $dir.basename($file);
$ext= pathinfo($path,PATHINFO_EXTENSION);
$extensions = array("JPG","jpg","jpeg","png");
$exts=strtolower($ext);
if (!in_array($exts, $extensions)) {
# code...
echo "sorry you donot have the right file format";
}
elseif ($_FILES['file']['size']>2000000) {
# code...
echo "your file is larger than 2mb";
}
elseif (file_exists($path)) {
# code...
echo "sorry a file already exists with this name change the name and try again";
}
else{
if (move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
# code...
echo basename($_FILES['file']['name']). "upload success";
}
else{
echo "file Upload failed";
}
}

There seem to be some random names being used in the $_FILES array in your PHP code. You use:
$file = $_FILES['file']['name'];
and then
elseif ($_FILES['promo0']['size']>2000000) {
and finally
if (move_uploaded_file($_FILES['image']['tmp_name'], $path)) {
Which is it? If you're not certain, you could var_dump($_FILES); and see what you have.

Related

Unable to upload image in codigniter, getting an wrong path error

I'm working on a project where I was trying to upload image by using jquery ajax + codeigniter.
Don't know why I'm getting following issue:
Error:
The upload path does not appear to be valid.
Is there anything i missed in following code?
upload_product_image() is the method that handle the upload task
public function upload_product_image()
{
if(isset($_FILES["file"]["name"]))
{
$config['upload_path'] = 'upload/';
$config['allowed_types'] = 'jpg|jpeg|png|gif|svg';
$config['max_width'] = 0;
$config['max_height'] = 0;
$config['max_size'] = 0;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if(!$this->upload->do_upload('file'))
{
echo 'Error: '. $this->upload->display_errors();
echo '<hr>';
echo $config['upload_path'];
}
else
{
$arr_image = array('upload_data' => $this->upload->data());
print_r($arr_image);
}
}
}
Following code is the HTML Code
<div class="card mb-2">
<a class="card-link" data-toggle="collapse" href="#collapseone">
<div class="card-header">
Upload Product Image(One) <span class="float-right text-danger">Size(192X138)</span>
</div>
</a>
<div id="collapseone" class="collapse show" data-parent="#accordion">
<div class="card-body">
<div class="form-group row" >
<div class="col-sm-3 text-center" style="position:relative;">
<img id="product_img_one_img_preview" src="upload/default/coming_soon.svg" class="w-100 img-fluid img-thumbnail" />
<i class="fa fa-upload"></i> Upload file
<div id="product_img_one_loader"></div>
</div>
<div class="col-sm-9 my-auto">
<input type="text" class="form-control" value="upload/default/coming_soon.svg" name="product_img_one" id="product_img_one" class="form-control" />
<input type="file" name="" class="form-control-file border hidden" id="product_img_one_box">
</div>
</div>
</div>
</div>
And following is the jQuery code that I used
<script>
$(document).ready(function() {
$("#product_img_one_loader").hide();
$('#product_img_one_box').on('change', function(){
var fd = new FormData();
var files = $(this)[0].files[0];
fd.append('file', files);
console.log(fd);
$.ajax({
url: 'https://mywebsite.com/shop/admin/upload_product_image',
type: "post",
data: fd,
contentType: false,
processData: false,
beforeSend: function() {
$("#product_img_one_loader").html('<div class="lds-facebook" style="position:absolute;top: 35%;left: 40%;"><div></div><div></div><div></div></div>');
$("#product_img_one_loader").show();
},
success: function(response) {
$("#product_img_one_loader").html('');
// $("#product_img_one_loader").hide();
$("#product_img_one_loader").html(response);
// alert(response);
// if (response != 0) {
//
// } else {
// alert('file not uploaded');
// }
},
complete: function(data) {
// $("#product_img_one_loader").html('');
// $("#product_img_one_loader").hide();
}
});
});
});
The upload path must be defined as an absolute server path, not a relative one.
Instead of $config['upload_path'] = 'upload/'; try $config['upload_path'] = FCPATH.'upload/';
That small change will force the upload to go in the upload directory which is located in the same directory as the front controller (CI's main index.php file).
Your current code is looking for an upload directory located in the same place as your controller (application/controllers/upload/), which is not what you want.
Also, check the directory and its contents are owned and writable by the PHP process (755 is a good place to start)... a simple -ls -l will give you all information you need on this matter

File upload with Jquery.fileupload.js in CodeIgniter - I can't find my error

The issue is I can't upload file to the folder but the file name is storing in DB. I am getting an image if I copy and paste an image to the folder but I can't able to upload while update or add an image.
I not good in jQuery. Also, this project using Jquery.file upload plugin which I really don't know.
product-edit.php
<div class="col-sm-6">
<table id="files" class="files">
<tr>
<td>
<div class="col-sm-12 text-center">
<img style="width: 300px; height: 200px;" src="<?= base_url() ?>userfiles/product/<?php echo $product['image'] . '?c=' . rand(1, 9999) ?>"/>
</div>
<div class="col-sm-12 my-2" > <?php echo $product['image'] ?> </div>
<div class="col-sm-12 my-2" >
<a class="btn-danger btn-sm px-1 " data-url="<?= base_url() ?>products/file_handling?op=delete&name=<?php echo $product['image'] ?>" class="aj_delete">
<i class="fa fa-trash mx-1 "></i>Delete Image</a>
</div>
</td>
</tr>
</table>
</div>
<div class="col-sm-6">
<span class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span class="my-2">Select files...</span>
<!-- The file input field used as target for the file upload widget -->
<input id="fileupload" type="file" name="files[]">
</span>
<div class="my-1">
<q>Allowed: gif, jpeg, png</q>
</div>
<!-- The global progress bar -->
<div id="progress" class="progress">
<div class="progress-bar progress-bar-success"></div>
</div>
</div>
</div>
jQuery
<script src="<?php echo assets_url('assets/myjs/jquery.ui.widget.js'); $invoice['tid'] = 0; ?>"></script>
<script src="<?php echo assets_url('assets/myjs/jquery.fileupload.js') ?>"></script>
$(function () {
'use strict';
// Change this to the location of your server-side upload handler:
var url = '<?php echo base_url() ?>products/file_handling?id=<?php echo $product['pid'] ?>';
$('#fileupload').fileupload({
url: url,
dataType: 'json',
formData: {'<?=$this->security->get_csrf_token_name()?>': crsf_hash},
done: function (e, data) {
var img = 'default.png';
$.each(data.result.files, function (index, file) {
$('#files').html('<tr><td><a data-url="<?php echo base_url() ?>products/file_handling?op=delete&name=' + file.name + '" class="aj_delete"><i class="btn-danger btn-sm icon-trash-a"></i> ' + file.name + ' </a><img style="max-height:200px;" src="<?php echo base_url() ?>userfiles/product/' + file.name + '"></td></tr>');
img = file.name;
});
$('#image').val(img);
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
Here the controller method for upload file to the folder
Products.php
public function file_handling()
{
if ($this->input->get('op')) {
$name = $this->input->get('name');
if ($this->products->meta_delete($name)) {
echo json_encode(array('status' => 'Success'));
}
} else {
$id = $this->input->get('id');
$this->load->library("Uploadhandler_generic", array(
'accept_file_types' => '/\.(gif|jpe?g|png)$/i', 'max_file_size' => 2048, 'upload_dir' => FCPATH . 'userfiles/product/', 'upload_url' => base_url() . 'userfiles/product/'
));
}
}
The problem is you are loading the upload library config but are not actually processing the upload.
After this, which loads the upload library wih your configuration:
$this->load->library("Uploadhandler_generic", array(
'accept_file_types' => '/\.(gif|jpe?g|png)$/i', 'max_file_size' => 2048, 'upload_dir' => FCPATH . 'userfiles/product/', 'upload_url' => base_url() . 'userfiles/product/'
));
You need to actually process the upload:
if (!$this->upload->do_upload('userfile'))
{
// do something if the upload processing fails. You can output the errors using $this->upload->display_errors()
}
else
{
// do something if the upload is successful
// upload data will be stored in $this->upload->data()
}
By doing this, Codeigniter will take the file from your server's tmp directory and do with it what you want (such as moving it to its destination). Change userfile for the name of the file field.
Please note that if you need to process multiple files at once you'll need to loop through all files (which means a little tweaking on the above code)

How to upload and save multiple photo in database

Please help me....
I want to upload up to 5 photos and save in database.
I want by selecting photo it will upload automatically and then the selected photo will appear in the page.
It will occure with one by one photo, up to 5 photos and the photos can be seen in the page.
Then if i submit it, it will save the photos (not the photo link) in a table named user in my database named my_db
<?php
include('dbcon.php');
session_start();
$session_id='1'; //$session id
?>
<html>
<head>
<title>Ajax Image Upload 9lessons blog</title>
</head>
<script type="text/javascript" src="scripts/jquery.min.js"></script>
<script type="text/javascript" src="scripts/jquery.wallform.js"></script>
<script type="text/javascript" >
$(document).ready(function() {
$('#photoimg').die('click').live('change', function() {
//$("#preview").html('');
$("#imageform").ajaxForm({target: '#preview',
beforeSubmit:function(){
console.log('v');
$("#imageloadstatus").show();
$("#imageloadbutton").hide();
},
success:function(){
console.log('z');
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
},
error:function(){
console.log('d');
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
} }).submit();
});
});
</script>
<style>
body
{
font-family:arial;
}
.preview
{
width:200px;
border:solid 1px #dedede;
padding:10px;
}
#preview
{
color:#cc0000;
font-size:12px
}
</style>
<body>
<div style="width:600px">
<div id='preview'>
</div>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload your image
<div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='imageloadbutton'>
<input type="file" name="photoimg" id="photoimg" />
</div>
</form>
</div>
</body>
</html>
And here ajaximage.php
<?php
include('dbcon.php');
session_start();
$session_id='1'; //$session id
$path = "uploads/";
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
$ext = getExtension($name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
$sql="INSERT INTO user (image, uid)
VALUES
('$actual_image_name','$session_id')";
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
else
echo "Fail upload folder with read access.";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
?>
There is a very good tutorial on how to do this using dropzone.js here http://www.infotuts.com/drag-drop-multiple-file-upload-with-dropzone-save-to-database/
Their php:
</p>
<?php
include 'db.php';
$upload_dir = 'myuploads';
function insert_data($ar){
$obj=new DB();
$key="(f_name , f_size, f_link,f_type,d_date)";
$val="('{$ar['fname']}', '{$ar['fsize']}','{$ar['flink']}','{$ar['ftype']}','{$ar['fdate']}')";
mysqli_query($obj->connection(),"INSERT INTO file_upload ".$key." VALUES ".$val);
//mysqli_close($obj->con);
}
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
// using DIRECTORY_SEPARATOR constant is a good practice, it makes your code portable.
$targetPath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . $upload_dir . DIRECTORY_SEPARATOR;
// Adding timestamp with image's name so that files with same name can be uploaded easily.
$fname = $targetPath.time().'-'. $_FILES['file']['name'];
$file_name=time().'-'. $_FILES['file']['name'];
$ftype=$_FILES["file"]["type"];
$fsize=($_FILES["file"]["size"] / 1024);
$tmpname=$_FILES["file"]["tmp_name"];
// Change $flink path to your folder where you want to upload images.
$flink='http://localhost/dragdrop%20file%20upload/myuploads/'.$file_name;
$arr= array('fname'=>$file_name,
'fsize'=>$fsize,
'flink'=>$flink,
'ftype'=>$ftype,
'fdate'=>date('Y-m-d h:i:s'));
insert_data($arr);
move_uploaded_file($tempFile,$fname);
}
?>
<p style="text-align: justify;">
Their html
<head>
<script src="./path/to/dropzone.js"></script>
</head>
<body>
<div id="main">
<p> Drag n Drop Your image files below - <b>InfoTuts</b></p>
</div>
<form action="file-upload.php" class="dropzone"></form>
</body>
My "Invoke Dropzone with some useful parameters"
var myNewDropzone = new Dropzone("#newuploadedForm", {
//Prepare the drop zone area
url: "<?php echo get_bloginfo('url'); ?>/path-to/your-ajax-file.php",
method: "POST",
uploadMultiple: true,
autoProcessQueue: false, /* Make this true if you don't want to handle the requests in your own Javascript - much easier! */
addRemoveLinks: false, /* Make true to let Dropzone handle remove document clicks */
clickable: true,
maxFiles: 10,
parallelUploads: 10,
maxFilesize: 50,
acceptedFiles:"image/png,image/gif,image/jpeg,application/pdf", /* change as needed and update the dictInvalidFileType below */
dictInvalidFileType: "Sorry, we only support .PNG, .JPG, .GIF, and .PDF files currently",
previewTemplate: document.querySelector('#preview-template').innerHTML, /* Remove this unless you create a preview template */
dictMaxFilesExceeded: "Sorry, you can upload a maximum of 10 images as pages. Please convert your images to one PDF document.",
/* Below is a commented out example of building your own client size file handler
init : function() {
this.on("addedfile", function(file) { new_file_added(file); });
//this.on("sending", function(file, xhr, formData) { sending_file(file, xhr, formData); });
this.on("thumbnail", function(file,fileurl) { new_thumbnail_added(file); });
this.on("removedfile", function(file) { new_file_removed(file); });
this.on("totaluploadprogress", function(progress) { display_progress(progress); });
this.on("queuecomplete", function() { all_files_uploaded(); });
//this.on("processing", function(file) { new_file_processed(file); });
} */
});
I think you will find dropzone works really well, and allows you do it the easy way (let dropzone take control) or slightly harder but you get full control of the upload process
If you want upload multiple photos to php server and save it in db.
First, you should dynamic add more input file element in front page, then in your ajaximage.php, check this reserved.variables.files, got everything you need to complete your task.

add progress bar to jquery ajax file upload

hey there i am using ajax to upload images. the codes are as follows.
index.php
<html>
<head>
</head>
<script src="js/jquery.min.js"></script>
<script src="js/jquery.wallform.js"></script>
<script>
$(document).ready(function() {
$('#photoimg').die('click').live('change', function() {
//$("#preview").html('');
$("#imageform").ajaxForm({target: '#preview',
beforeSubmit:function(){
console.log('ttest');
$("#imageloadstatus").show();
$("#imageloadbutton").hide();
},
success:function(){
console.log('test');
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
},
error:function(){
console.log('xtest');
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
} }).submit();
});
});
</script>
<style>
body
{
font-family:arial;
}
#preview
{
color:#cc0000;
font-size:12px
}
.imgList
{
max-height:150px;
margin-left:5px;
border:1px solid #dedede;
padding:4px;
float:left;
}
</style>
<body>
<div>
<div id='preview'>
</div>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaxImageUpload.php' style="clear:both">
<h1>Upload your images</h1>
<div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='imageloadbutton'>
<input type="file" name="photos[]" id="photoimg" multiple />
</div>
</form>
</div>
</body>
</html>
the ajaxImageUpload.php
<?php
error_reporting(0);
session_start();
$session_id='1'; //$session id
define ("MAX_SIZE","9000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "uploads/"; //a directory inside
foreach ($_FILES['photos']['name'] as $name => $value)
{
$filename = stripslashes($_FILES['photos']['name'][$name]);
$size=filesize($_FILES['photos']['tmp_name'][$name]);
//get the extension of the file in a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
if(in_array($ext,$valid_formats))
{
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname);
}
else
{
echo '<span class="imgList">You have exceeded the size limit!</span>';
}
}
else
{
echo '<span class="imgList">Unknown extension!</span>';
}
}
}
echo $uploaddir.$image_name;
?>
right now it displays an animated gif while it uploads the images. what i want to do is remove the gif and replace it with a progress bar but i have no clue how to do this and i am on a time schedule. could anyone please tell me how to do this. thanks!
The PHP code for processing the upload does not run until the entire file is uploaded, so it is not possible for you detect how much of the file has been uploaded in that script.
Generally you find upload progress bars built into a browser or some "client-side" program like a Flash application that can control that level of transfer.
For a strict PHP and Javascript implementation there are some workarounds that are fragile and a lot of work and are not very common (hence why you are asking here). There are some jQuery plugins that exist that can do this http://plugins.jquery.com/uploadfile/.

PHP file upload not working

I am trying to upload a picture but it always showing me the error. I think i have done everything it needs to upload a picture. Any help would be appreciated.
html:
<form action="../Code Files/User.php" method="post" enctype="multipart/form-data">
<div id="photo_settings2" style="margin-left:74px;">
<img id="Picture" src="../../img/User No-Frame.png"/>
</div>
<br><br><br><br>
<div id='Upload_Panel' style="margin-left: 32px;">
<input name='file' type='file' id='file_browse' onchange="readURL(this,'Picture')" style="cursor: pointer;"/>
</div>
<div id="delete" style="margin-top: -40px; margin-left: 198px; cursor: pointer">
<img src="../../img/Delete_Panel.png">
</div>
<div style="margin-left:144px; margin-top:-15px"></div>
<br><br>
</div>
</div>
</form>
php code:
$UploadDirectory = '/www/';
if(move_uploaded_file($_FILES['file']['file'], $UploadDirectory))
{
die('Success! File Uploaded.');
}
else
{
die('error uploading File!');
}
This should work:
if(move_uploaded_file($_FILES['file']['tmp_name'], basename($_FILES['file']['name'])))
{
die('Success! File Uploaded.');
}
else
{
die('error uploading File!');
}
Edit: I've changed the destination argument - now uploaded file will appear next to your php file. Remember about target folder permissions.
Working Code:
$UploadDirectory = '/wamp/www/img/Users/Users/'.basename($_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'], $UploadDirectory))
{
die('Success! File Uploaded.');
}
else
{
die('error uploading File!');
}

Categories