dropzonejs Unable to automatically submit - php

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);
}

Related

`$this->upload->do_upload()` is not working using ajax

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]);

You did not select a file to upload(codeigniter)

I am trying to upload a pic for which I have used the following code.
HTML:(I want that pic to be uploaded without submitting the form.)
<form id="chapThumb" method="post" action="<?php echo base_url();?>index.php/Admin/createChapter" enctype="multipart/form-data">
<input type="file" name="thumbpic" id="thumbpic">
<p class="FS12">Upload a thumbnail Image for the Chapter</p>
<input type="text" class="form-control" name="chname" placeholder="Enter chapter name"><br>
<input type="button" class="form-control" name="thumb" value="Upload" id="thumb">
<input class="dp-btn2" type="submit" value="Create" name="submit">
</form>
JQuery:
$(document).ready(function(){
$("#thumb").on('click',function(){
var x = $("#thumbpic").val();
console.log('x:'+x);
jQuery.ajax({
type: 'POST',
dataType: "json",
url: "<?php echo base_url();?>index.php/Admin/createChapterThumb",
data: {"thumbpic":x},
success:function(response){
console.log("response"+response);
var msg = response.message;
var stat = response.status;
var da = response.da;
console.log('msg:'+msg+',stat:'+stat+',da:'+da);
if(stat == 'success'){
//some code
}
else{
//some code
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Status: " + textStatus); console.log("Error: " + errorThrown);
}
});
});
});
Controller:
public function createChapterThumb(){
if($this->input->is_ajax_request()) {
$this->load->model('DPModel');
$config['upload_path'] = 'uploads/chapters/thumbs/temp';
$config['file_name'] = 'chapThumb';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('thumbpic'))
{
$data['status'] = 'error';
$data['message'] = $this->upload->display_errors();
echo json_encode($data);
}
else
{
$data['status'] = 'success';
$data['message'] = $this->upload->data();
echo json_encode($data);
}
exit;
}
//$res = $this->customerModel->insertChapter();
}
When upload button is clicked am getting the following error in console:
msg:You did not select a file to upload.,stat:error
Change the line $config['upload_path'] = 'uploads/chapters/thumbs/temp'; in controller function to below.
$config['upload_path'] = './uploads/chapters/thumbs/temp/';
Also, set the file permission of the folder to 777.

send 2 request with 1 ajax

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...

Using Ajax to upload file in codeigniter

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?

Ajax image upload refresh the page?

I am wondering that , why my page is getting refresh while i am using ajax to upload image, i tried to debug the problem, but did'nt find,
Here is the Controller function,
public function uploadImage() {
if(isset($_FILES['header_image'])) {
$config['upload_path'] = 'public/images/global/';
$config['allowed_types'] = 'gif|jpg|png';
$config['file_name'] = 'b_'.random_string('alnum', 5);
$this->upload->initialize($config);
if($this->upload->do_upload('header_image')) {
echo json_encode(array('status'=>"1", 'image_url'=>$this->upload->file_name));
} else {
$upload_error = array('error' => $this->upload->display_errors());
echo json_encode(array('status'=>"0",'upload_error'=>strip_tags($upload_error['error'])));
}
exit;
}
$this->template->render();
}
While my view uploadImage.php is look like,
$(document).ready(function() {
$('#header_image').on('change', function(){
$("#frm_global").ajaxForm({
success: function(data) {
res = $.parseJSON(data);
if(res.status == 1){
var html = "<img src='<?=base_url();?>path/"+res.image_url+"' class='preview' width='100' height='100' />";
html+= "<input type='hidden' id='image_url' name='image_url' value='"+res.image_url+"' >";
$("#preview").html(html);
$("#frm_global").ajaxFormUnbind();
}
if(res.status == 0){
$("#frm_global").ajaxFormUnbind();
}
}
}).submit();
});
});
<form name="frm_global" id="frm_global" enctype="multipart/form-data">
<div id="preview" style="float:left">
</div>
<div style="float:left">
<div style="margin-top:25px">
<input type="file" name="header_image" id="header_image"/>
<input style="margin-left:100px" onclick="" type="image" id="upload_header" src="any path" />
</div>
</div>
</form>
Sorry i think i didn't get your question properly.
But for submitting you can try like this
$("#theForm").ajaxForm({
url: 'server.php',
type: 'post',
success:function(data)
{
//do what you want to
}
});
may it helps you

Categories