im having trouble in uploading a multiple file by ajax . here is my code.
HTML code:-
<input type="file" id="txtBusinessImage" class="form-control" name="txtBusinessImageName[]" multiple >
<input type="hidden" id="selectBusinessHiddenID" name="selectBusinessHiddenID" value="<?php echo $viewCompanyResult->company_id; ?>">
<input type="button" id="uploadBusinessImg" value="Upload" >
Ajax Code:-
$("#uploadBusinessImg").on("click",function(e)
{
var fd = new FormData();
var file_data = $("#txtBusinessImage")[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
fd.append("file"+[i], file_data[i]);
}
var other_data = $("#selectBusinessHiddenID").serializeArray();
$.each(other_data,function(key,input){
fd.append(input.name,input.value);
});
$.ajax({
url: '<?php echo site_url('Main_ctrl/upload_business_photo_do'); ?>',
data: fd,
enctype: 'multipart/form-data',
contentType: false,
processData: false,
type: 'POST', async : true,
success: function(data){
alert(data);
}
});
});
When im calling upload_business_photo_do() function via Ajax then it does't able to recive the name of image $_FILES['file']['name']
upload_business_photo_do()
{
$business_hidden_id=$this->input->post('selectBusinessHiddenID');
/*code for image*/
$config['upload_path']='./upload_101/';
$config['allowed_types']= 'jpg|png|jpeg';
$config['max_width'] = '6000';
$config['max_height'] = '4500';
$this->load->library('upload',$config);
for($i=0; $i<count($_FILES['file']['name']); $i++)
{
$_FILES['userfile']['name']= $_FILES['file']['name'][$i];
$_FILES['userfile']['type']= $_FILES['file']['type'][$i];
$_FILES['userfile']['tmp_name']= $_FILES['file']['tmp_name'][$i];
$_FILES['userfile']['error']= $_FILES['file']['error'][$i];
$_FILES['userfile']['size']= $_FILES['file']['size'][$i];
if(! $this->upload->do_upload())
{
/*----set flash message*/
echo "error";
}
else
{
echo "done";
}
}
}
try to use like this , its simple and easy
$("#uploadBusinessImg").on("click",function(e)
{
var formData = new FormData($("#form_name")[0]);
$.ajax({
url: '<?php echo site_url('Main_ctrl/upload_business_photo_do'); ?>',
processData: false,
contentType: false,
data: formData,
type: 'POST', async : true,
success: function(data){
alert(data);
}
});
});
and in controller use like this
if($_FILES['txtBusinessImageName'])
{
$file_ary = $this->reArrayFiles($_FILES['txtBusinessImageName']);
foreach ($file_ary as $file)
{
print 'File Name: ' . $file['name'];
print 'File Type: ' . $file['type'];
print 'File Size: ' . $file['size'];
}
}
and also use this function for convert files data into array for multiple images data
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
its working perfect , just try to use it . you don't need to add a extra codes of files with ajax.
use form tag and submit button for file upload.
<form method="post" enctype="multipart/form-data">
<input type="file" id="txtBusinessImage" class="form-control" name="txtBusinessImageName[]" multiple >
<input type="hidden" id="selectBusinessHiddenID" name="selectBusinessHiddenID" value="<?php echo $viewCompanyResult->company_id; ?>">
<input type="submit" id="uploadBusinessImg" value="Upload">
</form>
and remove enctype: 'multipart/form-data', from ajax call and try.
Change following for fetching files:
var file_data = $('#txtBusinessImage').prop('files')[0];
var fd = new FormData();
fd.append('file', file_data);
Related
I have gone through many answers
How to upload file using ajax in codeigniter
File upload in codeigniter using ajax
which does not work with my code.
I want to upload word pdf img any sort of file using ajax.
This is my code:
Controller:
public function saveDetailData()
{
$rowId = $this->input->post('rowId',true);
$rowData = $this->input->post('rowData',true);
$rowColumn = $this->input->post('rowColumn',true);
$detailTableName = $this->input->post('detailTableName',true);
if($rowColumn == 'attachment'){
$filename2 = 'Query_'.rand(0,999999);
if( ! is_dir('uploads') ){mkdir('uploads',0777,TRUE); };
$path='uploads/queries/';
$imgtmpname=$_FILES['rowData']['tmp_name'];
$name = $_FILES["rowData"]["name"];
$ext = end((explode(".", $name)));
$fullpath= $path .$filename2.'.'.$ext;
$filename = $filename2;
move_uploaded_file($imgtmpname,$fullpath);
if ($ext <> '')
{
$fields = array(
'attachment' => $fullpath
);
}
else
{
$fields = array(
'attachment' => ''
);
}
}
$this->user_model->saveDetailData($rowId,$fields, $detailTableName);
echo "Successfully Saved";
}
View:
<?php echo form_open_multipart('editMatter');?>
<input onfocusout="saveDetailData1('<?php echo $detail->id; ?>',$(this).attr('name'),'attachment' )" type="file" id="attachment_<?php echo $detail->id; ?>" name="attachment_<?php echo $detail->id; ?>" value="">
<script>
function saveDetailData1(rowId,rowData,rowColumn) {
attachment = new FormData( $('#'+rowData)[0] );
$.ajax({
type: "POST",
url: "<?php echo base_url('user/saveDetailData')?>",
data: { '<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>',
'rowId': rowId,
'rowData' :attachment,
'rowColumn' :rowColumn,
'detailTableName': 'tbl_mattersdetail',
},
dataType:"JSON",
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(response){
//alert(response);
}
});
}
</script>
Try to modify the saveDetailData1 function like this :
function saveDetailData1(rowId,rowData,rowColumn) {
attachment = new FormData();
attachment.append('rowData', $('input[type=file][name="attachment_'+rowId+'"]')[0].files[0]);
$.ajax({
type: "POST",
url: "<?php echo base_url('user/saveDetailData')?>",
data: { '<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>',
'rowId': rowId,
'rowData' :attachment,
'rowColumn' :rowColumn,
'detailTableName': 'tbl_mattersdetail',
},
dataType:"JSON",
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(response){
//alert(response);
}
});
}
This will skip the rowData function parameter, but instead directly select the file input as the rowData ajax parameter.
In my code I have an input field having name product_image where I want to upload and insert multiple files into my database like this img1.jpg,img2.jpg,img3.jpg. But Now, what happen when I select 4 files i.e. img1.jpg,img2.jpg,img3.jpg,img4.jpg only img4.jpg store in my database and only this file are moving in my folder.
view:
<script>
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
product_name = $("#product_name").val();
var formData = new FormData();
$.each($("#product_image"), function (i, obj) {
$.each(obj.files, function (j, file) {
formData.append('product_image[' + i + ']', file);
});
});
formData.append('product_name', product_name);
$.ajax({
type:"POST",
data:formData,
processData: false,
contentType: false,
url:"<?php echo base_url(); ?>admin/products",
success:function(data){
$("#success_upload").html(data);
}
});
});
});
</script>
<input type="text" class="form-control" id="product_name" name="product_name">
<input type="file" id="product_image" name="product_image[]" multiple>
<input type="submit" class="btn btn-primary" id="submit" name="submit">
Controller:
public function products()
{
$dataInfo = array();
$files = $_FILES;
$cpt = count($_FILES['product_image']['name']);
for($i=0; $i<$cpt; $i++)
{
$_FILES['product_image']['name']= $files['product_image']['name'][$i];
$_FILES['product_image']['type']= $files['product_image']['type'][$i];
$_FILES['product_image']['tmp_name']= $files['product_image']['tmp_name'][$i];
$_FILES['product_image']['error']= $files['product_image']['error'][$i];
$_FILES['product_image']['size']= $files['product_image']['size'][$i];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload('product_image');
$upload_data = $this->upload->data();
$name_array[] = $upload_data['file_name'];
$fileName = $upload_data['file_name'];
$images[] = $fileName;
}
$fileName = $images;
$data = array(
'product_name' => $this->input->post('product_name'),
'product_image' => implode(",",$fileName),
);
$sql = $this->db->insert('add_product',$data);
if($sql == true)
{
echo '<p style="color:green;">New Product Added</p>';
}
else
{
echo '<p style="color:red;">Unable to Proceed!</p>';
}
}
private function set_upload_options()
{
$config = array();
$config['upload_path'] = FCPATH.'resource/product/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '1024';
$config['overwrite'] = FALSE;
return $config;
}
So, How can I upload and insert multiple files into my database? Please help me.
Thank You
I'm making a upload form and have chosen to do this with jQuery. The file gets uploaded but not into the desired folder, so im not parsing the data correct from the upload form to the process.
upload.php
<script>
$(document).ready(function()
{
var settings = {
url: "upload_process.php",
method: "POST",
allowedTypes:"jpg,jpeg,png",
fileName: "myfile",
galleryName: "<?php echo $gallery->folder; ?>",
multiple: true,
onSuccess:function(files,data,xhr)
{
$("#status").html("<font color='green'>Upload is success</font>");
},
onError: function(files,status,errMsg)
{
$("#status").html("<font color='red'>Upload is Failed</font>");
}
}
$("#mulitplefileuploader").uploadFile(settings);
});
</script>
upload_process.php
$galleryName = $_POST["galleryName"];
$output_dir = "media/images/".$galleryName."/";
if(isset($_FILES["myfile"])) {
$ret = array();
$error = $_FILES["myfile"]["error"];
{
/* Single File */
if(!is_array($_FILES["myfile"]['name'])) {
$fileName = $_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"], $output_dir . $_FILES["myfile"]["name"]);
$ret[$fileName] = $output_dir.$fileName;
/* Multiple files */
} else {
$fileCount = count($_FILES["myfile"]['name']);
for($i=0; $i < $fileCount; $i++) {
$fileName = $_FILES["myfile"]["name"][$i];
$ret[$fileName] = $output_dir.$fileName;
move_uploaded_file($_FILES["myfile"]["tmp_name"][$i],$output_dir.$fileName );
}
}
}
echo json_encode($ret);
}
The file is uploaded to media/images/ and can't see why the $galleryName is not set?
The parameter passing to the script does not seem to be right. You did not specify the exact jQuery plugin that is being used, so the below example might not work, but if so, it should at least give You a good hint about what to look for in the plugin documentation
Please remove the line
galleryName: "<?php echo $gallery->folder; ?>",
And replace with lines
enctype: "multipart/form-data", // Upload Form enctype.
formData: { galleryName: "<?php echo $gallery->folder; ?>" },
I'm trying to upload an image to a folder using ajax, jquery and php but the problem is that I don't know how to send my file input value to my php file, when I run my code I get the following message:
undefined index archivo
This is my ajax call (PD. All the other parameters works properly, I only have problems with the file input value)
function Registrar() {
var cat = $('#cat').val();
var nom = $('#name').val();
var desc = $('#description').val();
var image = $('#archivo').val();
//Also tried with this, to remove the fakepath string... $('input[type=file]').val().replace(/C:\\fakepath\\/i, '')
$.ajax({
url: '../../class/upload.php',
method: 'POST',
data: { categoria: cat, nombre: nom, descripcion: desc, archivo: image, activo: act, disponible: disp, precio: prec },
success: function (data) {
console.log(data);
}
});
}
PHP file:
<?php
$categoria = $_POST['categoria'];
$nombre = $_POST['nombre'];
$descripcion = $_POST['descripcion'];
$img = $_POST['archivo'];
$activo = $_POST['activo'];
$disponible = $_POST['disponible'];
$precio = $_POST['precio'];
$IdCategoria = 0;
$filepath = "";
//Imagen
if($categoria=="Piano") {
$IdCategoria = 1;
$filepath = "../Files/Productos/Piano/".$img;
}
$filetmp = $_FILES['archivo']['tmp_name'];
move_uploaded_file($filetmp, $filepath);
echo $IdCategoria.$nombre.$descripcion.$filepath.$activo.$disponible.$categoria.$precio;
?>
And the important parts of my HTML:
<form id="registerForm" method="post" role="form" enctype="multipart/form-data" >
<input name="archivo" id="archivo" style="width: 70%;" name="textinput" class="btn btn-block" type="file" onchange="showimagepreview(this)" />
EDIT: showimagepreview
function showimagepreview(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementsByTagName("img")[0].setAttribute("src", e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
How can I solve this?
Send your form data like this:
var formData = new FormData($("form")[0]);
$.ajax({
url: '../../class/upload.php',
method: 'POST',
data: formData,
success: function (data) {
console.log(data);
}
});
And you have to get the file with $_FILES, you can not get it in $_POST in php code.
Here is you solution
HTML
<form id="registerForm" method="post" enctype="multipart/form-data">
<input name="archivo" id="archivo" style="width: 70%;" class="btn btn-block" type="file" onchange="PreviewImage(this)" />
<img id="uploadPreview" />
<button type="submit">Submit</button>
Java Script
function PreviewImage() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("image").files[0]);
oFReader.onload = function (oFREvent) {
document.getElementById("uploadPreview").src = oFREvent.target.result;
};
};
//ajax
$("#registerForm").submit(function(event) {
var formData = new FormData($(this)[0]);
if ($(this).valid()) {
$.ajax({
url : '../../class/upload.php',
type : 'POST',
data : formData,
contentType : false,
cache : false,
processData : false,
success: function(e) {alert(e) },
error : function(x, t, m) {},
});
}
});
PHP
<?php
echo "<pre>"; print_r($_FILES);echo "</pre>"; die; //this will show you the file transfered by form.
$categoria = $_POST['categoria'];
$nombre = $_POST['nombre'];
$descripcion = $_POST['descripcion'];
$img = $_POST['archivo'];
$activo = $_FILES['activo'];
$disponible = $_POST['disponible'];
$precio = $_POST['precio'];
$IdCategoria = 0;
$filepath = "";
//Imagen
if($categoria=="Piano") {
$IdCategoria = 1;
$filepath = "../Files/Productos/Piano/".$img;
}
$filetmp = $_FILES['archivo']['tmp_name'];
move_uploaded_file($filetmp, $filepath);
echo $IdCategoria.$nombre.$descripcion.$filepath.$activo.$disponible.$categoria.$precio;
?>
change this
$img = $_POST['archivo'];
to
$_FILES['archivo'];
Files object cannot be recieved in $_POST
I have this script that will upload multiple files and it will be retrieve by the controller.
Question
How can I put another data in the data: section in the AJAX request for example like this:
data: data + '&reference='+$('#ref').val(),
controller
function insertAttachment() {
$i = 0;
$referenceNo = $this->input->post('reference');
if(!isset($_FILES[$i]) ) {
}
else {
$x = $_FILES[$i]['name'];
$xx = explode('.', $x);
$config['upload_path'] = 'MRS-files\Upload_files';
$config['allowed_types'] = 'xls|doc|jpg|png|gif|pdf';
$this->load->library('upload',$config);
for($i; $i <= 4; $i++) {
$counter = $_FILES;
while ( $i <= count($counter) ) {
$x = $_FILES[$i]['name'];
$xx=explode(".", $x);
$config['file_name']= 'IT2015' .'('. ($i+1) .').'. $xx[1];
$this->upload->initialize($config);
$_FILES['up']['name'] = $_FILES[$i]['name'];
$_FILES['up']['tmp_name'] = $_FILES[$i]['tmp_name'];
$_FILES['up']['type'] = $_FILES[$i]['type'];
$_FILES['up']['size'] = $_FILES[$i]['size'];
if ( ! $this->upload->do_upload('up')) {
//error on uploading
echo str_replace('','',$this->upload->display_errors()); //temporary commented no use cause of redirect to homepage
//$this->cancelREC();
exit();
}
else {
$data = array('upload_data' => $this->upload->data());
$this->edit_development_model->insertonAttachments($data['upload_data'] , $referenceNo);
$i++;
}
}
}
}
}
Here is the script:
function EditUploadImage() {
var data = new FormData($('input[name^="edit_files"]'));
jQuery.each($('input[name^="edit_files"]')[0].files, function(i, file) {
data.append(i, file);
});
$.ajax ({
type: 'POST',
data: data,
url: 'mis.php/edit_development_detailsControl/updateRequest',
cache: false,
contentType: false,
processData: false,
success: function(data) {
alert(data);
//messagealert("Success","You're Request have been save successfully");
}
});
}
Hope this one help you.
var fd = new FormData();
var file_data = $('input[type="file"]')[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
fd.append("file_"+i, file_data[i]);
}
var other_data = $('form').serializeArray();
$.each(other_data,function(key,input){
fd.append(input.name,input.value);
});
$.ajax({
url: 'test.php',
data: fd,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
console.log(data);
}
});