I have a project codeigniter and I will use ajax for form submission.My first problem is $this->upload->do_upload is always false. I did search for some answers but I cannot get the job done.
I tried this link to solve my problem but didnt help.
Ajax upload not working codeigniter
How to Upload files using Codeigniter and Ajax [Complete Tutorial]
Hope someone can help me.Below is my code.
View
<form id="form-register" enctype="mutlipart/form-data" action="" method="POST">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<div class="form-group form-file-upload form-file-multiple ">
<input type="file" class="inputFileHidden" name="client_img" id="client_img">
<div class="fileinput-new thumbnail img-raised">
img class="img-fluid" src="<? echo base_url();?>assets/img/person.png" alt="client-img" />
</div>
<div class="input-group mt-2">
<span class="input-group-btn">
<button type="button" class="btn btn-fab btn-round btn-primary">
<i class="material-icons">attach_file</i>
</button>
</span>
<input type="text" class="form-control inputFileVisible" placeholder="Choose client picture.." require>
</div>
</div>
</div>
</div>
Controller.php
public function register_client()
{
$validator = array('success' => false, 'messages' => array());
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|png|jpeg|gif';
$config['encrypt_name'] = TRUE;
$this->load->library('upload',$config);
if(!$this->upload->do_upload('client_img')){
$validator['success'] = false;
$validator['messages'] = $this->input->post('client_img');
}else{
$data = $this->upload->data();
//Resize and Compress Image
$config['image_library'] = 'gd2';
$config['source_image'] = './uploads/'.$data['file_name'];
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = FALSE;
$config['quality'] = '60%';
$config['width'] = 600;
$config['height'] = 400;
$config['new_image'] = './uploads/'.$data['file_name'];
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$client_data = array(
'account_no' => 1000,
'client_img' => $data['file_name'],
'mname' => $this->input->post('mname'),
'gname' => $this->input->post('gname'),
'lname' => $this->input->post('lname'),
'email' => $this->input->post('email'),
'number1' => $this->input->post('number1'),
'number2' => $this->input->post('number2'),
'purok_no' => $this->input->post('purok_no'),
'barangay' => $this->input->post('barangay'),
'city' => $this->input->post('city'),
'postal_code' => $this->input->post('postal_code'),
'birthdate' => $this->input->post('birthdate'),
'gender' => $this->input->post('inlineRadioOptions'),
'info' => $this->input->post('info')
);
$insert_data = $this->claims_model->insert_client($client_data);
if($insert_data == true){
$validator['success'] = true;
$validator['messages'] = 'loan';
}else{
$validator['success'] = false;
$validator['messages'] = 'Something went wrong';
}
}
echo json_encode($validator);
}
Ajax.js
$(document).ready(function(e) {
$(".client-save").click(function(e) {
e.preventDefault();
var formdata = new FormData(document.getElementById("form-register"));
if (formdata) {
$.ajax({
type: "POST",
url: "register",
dataType: "json",
data: formdata,
processData: false,
contentType: false,
cache: false,
success: function(response) {
if (response.success == true) {
alert(response.messages);
} else {
showNotification("top", "right", response.messages);
}
}
});
}
});
});
Hope someone can site my problem for this one. I try modified the ajax code but still the
$this->upload->do_upload()
is still in false.
You can call the display_errors() method to help you with debugging, just add this where you return the response:
echo "<pre>";
die(var_dump( $this->upload->display_errors() ));
echo "</pre>";
Also if you are on mac/linux make sure that you have write permissions to your uploads folder, also you should check if it exists before writing to it:
if (!is_dir('uploads')) {
mkdir('./uploads', 0777, true);
}
as you need to append image file, you can try following code
var formData = new FormData();
formData.append('client_img', $('#client_img')[0].files[0]);
Related
Hi i am having a page where user can insert the blogs which contains blog name,image and description.Getting the problem while inserting blogs in database.If i am removing the mandatory option for blog image unable to insert the post into database.It is displaying blog has successfully inserted but there is no blog inserted in my database.
Controller:
function addblogs()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<br /><span class="error"> ','</span>');
$this->form_validation->set_rules('blog_title','Blog Title');
$this->form_validation->set_rules('description','Blog Description');
if($this->form_validation->run()== FALSE)
{
$data['mainpage']='blogs';
$data['mode']='add';
$this->load->view('templates/template',$data);
}
else
{
$this -> blogs_model -> insertblogs();
$this->flash->success('<h2>blogs Added Successfully!</h2>');
redirect('blogs');
}
}
Model:
function insertblogs()
{
$data=array(
'blog_title'=>$this->input->post('blog_title'),
'description'=>$this->input->post('description'),
);
if ( $_FILES AND $_FILES['image_path']['name'])
{
$file_name = $this->do_upload2();
if(is_array($file_name)){
$error['imageerror'] = $file_name['error'];
}
else
$data['image_path']=$file_name;
}
if(!isset($data['image_path']) && !isset($error['imageerror']))
$error['imageerror'] ="Please Upload an image";
if(isset($error))return $error;
$this->db->insert('blogs',$data);
}
function do_upload2()
{
$config = array(
'allowed_types' => 'jpg|jpeg|gif|png',
'upload_path' => $this->image_path,
'max_size' => 20000,
'maintain_ratio'=>FALSE,
'width' => 90,
'height' => 75
);
$this->load->library('upload', $config);
if(!$this->upload->do_upload('image_path'))
{
return $error = array('error' => $this->upload->display_errors());
}
else
{
$image_data = $this->upload->data();
$config = array(
'source_image' => $image_data['full_path'],
'new_image' =>$this->image_path . '/thumbs',
'maintain_ratio' => FALSE,
'width' => 90,
'height' => 75
);
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$filename =time().preg_replace('/[^A-Za-z0-9\s.\s-]/', '_', $image_data['file_name']);
rename($image_data['full_path'],$image_data['file_path'].$filename);
rename($image_data['file_path'].'thumbs/'.$image_data['file_name'],$image_data['file_path'].'thumbs/'.$filename);
return $filename;
}
}
View:
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function(){
if((jQuery.trim($('#image_path').val())==''))
{
alert("Please select image");
$('#image_path').focus();
return false;
}
});
});
</script>
<div class="full_w">
<div class="h_title">
<div class="lefttitle fl">
Add Blogs
</div>
<div class="rightbutton fr">
<a class="button cancel" href="<?php echo site_url()?>/blogs">Cancel</a>
</div>
</div>
<?php
$form_attributes = array('name'=>'adds', 'id'=>'adds', 'enctype' => "multipart/form-data");
echo form_open('blogs/addblogs',$form_attributes);
?>
<div class="element">
<label for="blogtitle"><font color ="black">Blog Title</font></label>
<input class="text err" type="text" name="blog_title" id="blog_title" value="<?php echo set_value('blog_title');?>"/>
</div>
<div class="element">
<label for="description"><font color ="black">Blog Description</font></label>
<textarea name="description" class="ckeditor" rows="4" cols="173"></textarea>
</div> <br/>
<div class="element">
<label><font color ="black">Select Image:</font></label>
<input class="err" type="file" name="image_path" id="image_path"/>
</div><br/>
<div align="center">
<input type="submit" id="submit" value="Submit" />
</div>
<div class="clear"></div>
<?php echo form_close();?>
</div>
</div>
<div class="clear"></div>
I am using codeigniter php
From insert blog section commented three lines now its working fine.
if ( $_FILES AND $_FILES['image_path']['name'])
{
$file_name = $this->do_upload2();
if(is_array($file_name)){
$error['imageerror'] = $file_name['error'];
}
else
$data['image_path']=$file_name;
}
//if(!isset($data['image_path']) && !isset($error['imageerror']))
//$error['imageerror'] ="Please Upload an image";
//if(isset($error))return $error;
i manage to insert the uploaded photo into databases as well as into the specified path, the problem is the photo that i uploaded not inserting to the logging user column instead its create another column, am i missing something? below are my codes and also screenshot in case you guys hardly understand what i meant
MODEL
function create($data){
$query = $this->db->insert('dosen', $data);
return $query;
}
CONTROLLER
public function Upload(){
$upload = $this->input->post('fotoDsn');
//Foto Set
$photoName = gmdate("d-m-y-H-i-s", time()+3600*7).".jpg";
$config['upload_path'] = './assets/';
$config['allowed_types'] = 'gif||jpg||png';
$config['max_size'] = '2048000';
$config['file_name'] = $photoName;
$this->load->library('upload',$config);
if($this->upload->do_upload('userfile')){
$upload = 1;
}
else{
$upload = 2;
}
if($upload==1){
$data = array(
'foto_dosen'=>$photoName);
$insert = $this->MDosen->create($data);
if($insert){
echo 1;
}else{
echo 2;
}
}//else kalo gagal
}
VIEW
<i class="material-icons tiny">assignment_ind</i> Upload
<div id="modalUpload" class="modal" style="width: 40%; height: auto">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<i class="medium material-icons prefix">assignment_ind</i>
<h4 class="modal-title"> Upload Foto</h4>
</div>
<div class="modal-body">
<form action="upload" id="tambahFormUpload" method="post" enctype="multipart/form-data">
<div class="file-field input-field">
<div class="btn">
<span>File</span>
<input type="file" name="userfile">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" >Simpan</button>
</div>
</form>
</div>
</div>
</div>
</div>
JS
$('.upload').click(function(){
id1 = $(this).attr('id');
});
$('#tambahFormUpload').submit(function(e){
alert(id1);
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url:'Profil/Upload/'+id1,
data:formData,
type:'POST',
contentType: false,
processData: false,
success:function(data){
$("#modalUpload").hide();
window.location.reload(true);
}
});
});
based on #Sean comment it is true that instead using insert, we should use update, so the correct controller will look like this, using update model rather than create and put parameter on my function, on second though the reason why it's not insert into the correct column because the id of the user can't be found (where clause), so with update we can set the where clause and point it into the user id, Hope this help
CONTROLLER
public function Upload($id){
$upload = $this->input->post('fotoDsn');
//Foto Set
$photoName = gmdate("d-m-y-H-i-s", time()+3600*7).".jpg";
$config['upload_path'] = './assets/';
$config['allowed_types'] = 'gif||jpg||png';
$config['max_size'] = '2048000';
$config['file_name'] = $photoName;
$this->load->library('upload',$config);
if($this->upload->do_upload('userfile')){
$upload = 1;
}
else{
$upload = 2;
}
if($upload==1){
$data = array(
'foto_dosen'=>$photoName);
$update = $this->MDosen->update(array('id'=>$id), $data);
if($update){
echo 1;
}else{
echo 2;
}
}//else kalo gagal
}
MODEL
function update($cond, $data){
$this->db->where($cond);
$query = $this->db->update('dosen', $data);
return $query;
}
Environment:php+dropzone.js+CI(codeigniter)
Server can not execute uploading.But browser console can output info.
<div class="panel-body">
<div class="form-group">
<label class="control-label">File Upload</label>
<div class="controls">
<form action="Upload/do_upfile" class="dropzone" id="myDropzone">
<div class="fallback">
<input name="userfile" type="file" multiple="" />
</div>
</form>
</div>
</div>
script:
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("#myDropzone", {
url: "Upload/do_upfile",
method: 'post',
addRemoveLinks: true,
uploadMultiple: true,
init: function() {
this.on("addedfile", function(file) {
console.log("File " + file.name + "add");
});
this.on("success", function(file) {
console.log("File " + file.name + "uploaded");
});
this.on("removedfile", function(file) {
console.log("File " + file.name + "removed");
});
}
});
php ci controllers
public function do_upfile()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|css';
//$config['max_size'] = 100000;
//$config['max_width'] = 1024;
//$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
Browsers, upload is normal, the console input also has content, but not execute on the server, ths!
You have to return (json_encoded) string.
In your controller:
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
echo json_encoded($error);
}
else
{
$data = array('upload_data' => $this->upload->data());
echo json_encoded($data);
}
I am upload an image in one my form but its always giving me an error like
"A PHP Error was encountered Severity: Notice Message:
Undefined index: vimage Filename: controllers/vouchers.php Line
Number: 42"
My View File code :
<?php echo form_open_multipart(site_url("promotions/add_item/"), array("class" => "form-horizontal","id"=>"addItem")) ?>
<div class="form-group">
<label class="col-sm-3 control-label">Show on</label>
<div class="col-sm-3">
Artist Directory : <input type="checkbox" name="artist_dir" value='1'>
</div>
<div class="col-sm-3">
Highlight : <input type="checkbox" name="highlight" value='1'>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Title</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="title" id="title" placeholder="Title">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Image</label>
<div class="col-sm-9">
<input type="file" name="pro_image">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Description</label>
<div class="col-sm-9">
<textarea class="form-control" rows="3" name="description" placeholder="Description"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9">
<button type="submit" class="btn btn-success" name="submit" id="submit">Submit</button>
</div>
</div>
<?php echo form_close() ?>
My Controller Code :
<pre>
public function add_item(){
$this->load->library('upload');
$this->form_validation->set_rules('title','Title','required');
$this->form_validation->set_rules('description','Description','required');
print_r($_FILES['pro_image']);
if ($_FILES['pro_image']['size'] > 0) {
$this->upload->initialize(array(
"upload_path" => './uploads/',
"overwrite" => FALSE,
"encrypt_name" => TRUE,
"remove_spaces" => TRUE,
"allowed_types" => "gif|jpg|png|jpeg",
));
if (!$this->upload->do_upload('vimage')) {
$this->upload->display_errors();
}
$data = $this->upload->data();
echo 'img : '.$img = $data['file_name'];
}
exit;
if($this->form_validation->run()==FALSE){
echo '<div class="alert alert-dismissable alert-danger"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><small>'. validation_errors().'</small></div>';
}
else {
$title = $this->input->post('title');
$description = $this->input->post('description');
$artist_dir = $this->input->post('artist_dir');
$highlight = $this->input->post('highlight');
$this->promotions_model->add_item($title, $description,$artist_dir,$highlight);
}
}
</pre>
please let me know what i am doing wrong here
Try this
if ($_FILES['vimage']['size'] > 0) {
$this->load->library('upload');
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload();
$fileName = $_FILES['vimage']['name'];
private function set_upload_options()
{
// upload an image options
$config = array();
$config['upload_path'] = './upload/'; //give the path to upload the image in folder
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
return $config;
}
For more read this Link
Try this
if (!empty($_FILES['vimage']))
{
$config['upload_path'] = './uploads/';
//$config['max_size'] = '102400';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['overwrite'] = FALSE;
$config['remove_spaces'] = TRUE;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('vimage'))
{
$this->session->set_flashdata('error', $this->upload->display_errors());
//redirect('controller/method');
}
else
{
$this->session->set_flashdata('success', 'Image Has been Uploaded');
//redirect('controller/method');
$img = $data['file_name'];
}
}
Please check first,
print_r(_FILES);
If you get files array then you can use below code for uploading image.
function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
// You can give Image formats if you want to upload any video file.
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' = $this->upload->display_errors());
// uploading failed. $error will holds the errors.
}
else
{
$data = array('upload_data' => $this->upload->data());
// uploading successfull, now do your further actions
}
}
I have added your code in my system it's working for fine for me.
public function add(){
$this->load->library('upload');
$this->load->helper('form');
$this->load->helper('url');
print_r($_FILES);die;
$this->form_validation->set_rules('title','Title','required');
$this->form_validation->set_rules('description','Description','required');
if ($_FILES['pro_image']['size'] > 0) {
$this->upload->initialize(array(
"upload_path" => './uploads/',
"overwrite" => FALSE,
"encrypt_name" => TRUE,
"remove_spaces" => TRUE,
"allowed_types" => "gif|jpg|png|jpeg",
));
if (!$this->upload->do_upload('vimage')) {
$this->upload->display_errors();
}
$data = $this->upload->data();
echo 'img : '.$img = $data['file_name'];
}
exit;
if($this->form_validation->run()==FALSE){
echo '<div class="alert alert-dismissable alert-danger"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><small>'. validation_errors().'</small></div>';
}
else {
$title = $this->input->post('title');
$description = $this->input->post('description');
$artist_dir = $this->input->post('artist_dir');
$highlight = $this->input->post('highlight');
$this->promotions_model->add_item($title, $description,$artist_dir,$highlight);
}
}
Well..I'm new to codeigniter. And I'm stuck on this problem from days!
I read many questions and answers telling about file upload using ajax. But I can't find a specific solution to my problem.
There is the View :
<?php echo form_open_multipart('upload/upload_cover', array("id" => "upload_file"));?>
<input type="file" id="coverpic" name="userfile" size="20" class="btn btn-primary" style="float: right"/>
<br /><br />
<input type="submit" name="submit" id="submit" class="btn btn-primary" style="float: right" value="Upload">
</form>
Controller : Upload, method upload_cover
public function upload_cover() {
$file = $_FILES['userfile']['tmp_name'];
$userid = $this->session->userdata('userid');
$ext = end(explode('.', $_FILES['userfile']['name']));
$_FILES['userfile']['name'] = "$userid.$ext";
$config['upload_path'] = './img/cover/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '200000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( !$this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$data['body'] = 'body_profile';
$data['error'] = $error;
$this->load->view('include/template_profile', $data);
}
else {
$cover = "$userid.$ext";
echo $cover;
$this->load->model('dbconnect');
$this->dbconnect->editCover($userid, $cover);
//$this->index();
$data = $this->upload->data();
$image_path = $data['full_path'];
if(file_exists($image_path))
{
echo json_encode($image_path);
}
//redirect('homepage/');
//echo base_url()."img/cover/".
}
Now my problem is... This code is working without ajax... I want to write this using Ajax, so that image is uploaded and shown in its div on clicking Upload button.
So what should I pass in data of ajax request to use the above controller method itself?
Thank you..
Well.. you need jquery.form this way:
$(document).ready(function() {
var $form = $('#myform');
var $btn = $('#submit'); // upload button
$btn.click(function() {
// implement with ajaxForm Plugin
$form.ajaxForm({
beforeSend: function() {
// xyz
},
success: function(img_url) {
$form.resetForm();
alert(img_url);
//$myimage.attr('src', img_url);
},
error: function(error_msg) {
alert('error:' + error_msg);
}
});
});
});
also you need return (or stored in json) an url from php :)
View :
<div class="upload" id="upload" style="display:none">
<form id="form-id" action="#" enctype="multipart/form-data" method="POST">
<input type="file" id="coverpic" name="userfile" size="20" class="btn btn-primary" style="float: right"/>
<br /><br />
<input type="submit" name="submit" id="submit" class="btn btn-primary" style="float: right" value="Upload" />
</form>
</div>
Controller : Upload, method upload_cover
public function upload_cover() {
$userid = $this->session->userdata('userid');
$config['upload_path'] = 'C:\wamp\www\Twitter_Project\img\cover';
$config['upload_url'] = base_url().'files/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000KB';
$config['max_width'] = '4096';
$config['max_height'] = '2160';
$config['overwrite'] = TRUE;
$config['file_name'] = $userid;
$this->load->library('upload', $config);
if (!$this->upload->do_upload())
{
//$error = array('error' => $this->upload->display_errors());
//$this->load->view('upload_form', $error);
echo "error";
}
else
{
//$username = $this->session->userdata('username');
$ext = end(explode('.', $_FILES['userfile']['name']));
$data = "$userid.$ext";
//$data = array('upload_data' => $this->upload->data());
$this->load->model('dbconnect');
$this->dbconnect->editCover($userid, $data);
//$this->load->view('upload_success', $data);
echo json_encode($data);
}
#unlink($_FILES['userfile']);
echo 'unlinked user file';
}
Ajax method :
$('#form-id').on('submit', function(event){
event.preventDefault();
var data = new FormData($(this)[0]);
$.ajax({
url: base + 'upload/upload_cover',
type: 'POST',
dataType: 'json',
data: data,
processData: false,
contentType: false,
cache: false
}).done(function(data) {
if(data !== 'error'){
console.log("success");
console.log(data);
var path = base + 'img/cover/' + data;
console.log(path);
console.log( $('#sp1')[0].src);
//$('#sp1')[0].src = path;
$('#sp1').attr('src',path);
}
else{
alert("Cannot upload your cover picture. Please try again.");
}
})
});
This is a working solution, one will have to write only the model method separately.
Now, I dont want to get the previously saved image name to unlink so here I overwrite the image. Is there a way to overwrite the cached image other than changing filename?