Using Ajax to upload file in codeigniter - php

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?

Related

Upload multiple files using multiple input fields

I have several input fields in my view that are like this
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo form_open_multipart('info/normal_upload');?>
<input type="file" name="one" size="20" />
<input type="file" name="two" size="30" />
<input type="file" name="three" size="40" />
<br /><br />
<input type="submit" value="upload" />
</form>
</body>
</html>
I am uploading the files like this
$config['upload_path'] = realpath(FCPATH.'uploads');
$config['allowed_types']= "gif|jpg|png|jpeg|pdf";
$config['overwrite'] = TRUE;
$config['max_size'] = "2048000";
$config['max_height'] = "5000";
$config['max_width'] = "5000";
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('one'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('normal_upload', $error);
}
if ( ! $this->upload->do_upload('two'))
{
$error = array('error' => $this->upload->display_errors());
//$this->load->view('normal_upload', $error);
}
if ( ! $this->upload->do_upload('three'))
{
$error = array('error' => $this->upload->display_errors());
//$this->load->view('normal_upload', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
echo $data['upload_data']['full_path'].'<br/>';
//$this->load->view('normal_upload', $data);
}
I would like to get the file names,paths of all files uploaded. If i select files in all form fields, the files are getting uploaded but this:
echo $data['upload_data']['full_path'].'<br/>';
only gets one file path. How can i get the file paths and rename the files uploaded?
Loading the library with $this->load->library('upload', $config); works when you're uploading just one file. However when you're uploading more than one file you need to reinitialize the library with the config.
More information about this here:
https://codeigniter.com/userguide3/libraries/file_uploading.html#initializing-the-upload-class
Like so:
$this->load->library('upload');
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('one'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('normal_upload', $error);
}
$data['one'] = array('upload_data' => $this->upload->data());
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('two'))
{
$error = array('error' => $this->upload->display_errors());
//$this->load->view('normal_upload', $error);
}
$data['two'] = array('upload_data' => $this->upload->data());
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('three'))
{
$error = array('error' => $this->upload->display_errors());
//$this->load->view('normal_upload', $error);
}
$data['three'] = array('upload_data' => $this->upload->data());
Then you can access the file data with something like:
$data['one']['upload_data']['full_path'];
$data['two']['upload_data']['full_path'];
$data['three']['upload_data']['full_path'];
Turns out its not that straight forward. The following code:
Uploads image files and pdfs only, only images and pdfs are allowed
Renames uploaded files
Strips all spaces in uploaded files
public function normal_upload(){
$uploadLocation = "uploads/";
$uploadMainTo = null;
if(isset($_FILES['MainImage'])){
$path = $_FILES['MainImage']['name']; // file means your input type file name
$ext = pathinfo($path, PATHINFO_EXTENSION);
if ($ext=="jpg" OR $ext=="jpeg" OR $ext=="gif" OR $ext=="png" OR $ext=="pdf") {
echo "Upload successful";
}else{
// your invalid code here like...
echo "Invalid image format. Only upload JPG or JPEG or GIF or PNG";
header('Location: http://localhost/upload_app/info/nu');
exit;
}
$main_image_name = $_FILES['MainImage']['name'];
$main_image_size = $_FILES['MainImage']['size'];
$main_image_tmp = $_FILES['MainImage']['tmp_name'];
$uploadMainTo = $uploadLocation.sa(time().mt_rand(43,672882).bin2hex(random_bytes(16)).trim($main_image_name));
$moveMain = move_uploaded_file($main_image_tmp,$uploadMainTo);
echo $uploadMainTo.'<br/>';
}
$uploadSecondTo = null;
if(isset($_FILES['SecondImage'])){
$path = $_FILES['SecondImage']['name']; // file means your input type file name
$ext = pathinfo($path, PATHINFO_EXTENSION);
if ($ext=="jpg" OR $ext=="jpeg" OR $ext=="gif" OR $ext=="png" OR $ext=="pdf") {
// your code here like...
echo "Upload successful";
}else{
// your invalid code here like...
echo "Invalid image format. Only upload JPG or JPEG or GIF or PNG";
header('Location: http://localhost/upload_app/info/nu');
exit;
}
$second_image_name = $_FILES['SecondImage']['name'];
$second_image_size = $_FILES['SecondImage']['size'];
$second_image_tmp = $_FILES['SecondImage']['tmp_name'];
$uploadMainTo = $uploadLocation.sa(time().mt_rand(43,672882).bin2hex(random_bytes(16)).trim($main_image_name));
$moveSecond = move_uploaded_file($second_image_tmp,$uploadSecondTo);
echo $uploadSecondTo.'<br/>';
}
$uploadPdfTo = null;
if(isset($_FILES['PDF'])){
$path = $_FILES['PDF']['name']; // file means your input type file name
$ext = pathinfo($path, PATHINFO_EXTENSION);
if ($ext=="jpg" OR $ext=="jpeg" OR $ext=="gif" OR $ext=="png" OR $ext=="pdf") {
// your code here like...
echo "Upload successful";
}else{
// your invalid code here like...
echo "Invalid image format. Only upload JPG or JPEG or GIF or PNG";
header('Location: http://localhost/upload_app/info/nu');
exit;
}
$pdf_name = $_FILES['PDF']['name'];
$pdf_size = $_FILES['PDF']['size'];
$pdf_tmp = $_FILES['PDF']['tmp_name'];
$uploadMainTo = $uploadLocation.sa(time().mt_rand(43,672882).bin2hex(random_bytes(16)).trim($main_image_name));
$movepdf = move_uploaded_file($pdf_tmp,$uploadPdfTo);
echo $uploadPdfTo.'<br/>';
}
}
define a helper sa_helper.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('sa')){
function sa($string){
return str_replace(' ', '', $string);
}
}
?>
and this is your view
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo form_open_multipart('info/normal_upload');?>
<input type="file" name="PDF">
<input type="file" name="MainImage">
<input type="file" name="SecondImage">
<br /><br />
<input type="submit" value="upload" />
</form>
</body>
</html>
To upload files using jquery, use this form, it works as well
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#form_img").submit(function(e){
e.preventDefault();
var formData = new FormData($("#form_img")[0]);
$.ajax({
url : $("#form_img").attr('action'),
type : 'POST',
data : formData,
contentType : false,
processData : false,
success: function(resp) {
console.log(resp);
}
});
});
});
</script>
<form action="http://localhost/upload_app/info/normal_upload" id="form_img" method="GET" role="form" enctype="multipart/form-data">
<input type="file" name="PDF">
<input type="file" name="MainImage">
<input type="file" name="SecondImage">
<button type="submit">Submit </button>
</form>

PHP multipart/form Data

I'm trying to upload a file , but file name is a variable,so to do that I have get the name of input type(i can do it by getting all data on post and run a loop and get the keyname)
then I'm getting all post data , but then it returns me a empty array,when I remove multipart/form data from the form it will return the array with the value.then I can get the file type name, but it doesn't upload the file because I remove the multipart from the form.
How can I do this? if read the code u will understand. Please help me to do this.
This is my view page
public function addTest($app_id)
{
$data=$this->input->post();
$id=$this->session->userdata['loggedHospitalData']['hp_id'];
while ($test = current($data)) {
$dataArr=array(
"hospital_id" => $id,
);
$test_id=key($data);
$wherArr = array("test_id"=>$test_id);
//$result = $this->Hospital_model->updateTestData($dataArr,$wherArr);
$report=$this->input->post($test_id);
$config['upload_path'] = './uploads/';
$config['allowed_types'] = '*';
$config['max_size'] = 5000000000000;
$config['max_width'] = 10240;
$config['max_height'] = 10240;
$this->load->library('upload', $config);
if (!$this->upload->do_upload($report))
{
$error = array('error' => $this->upload->display_errors());
}
else
{
$data1 = array('upload_data' => $this->upload->data());
}
/*$dataRepArr=array(
"r_test_id " => $test_id,
"file" => $photo1,
);*/
next($data);
//header('Location: http://localhost/docto/index.php/Hospital/patientView/'.$app_id);
}
}
And this my View
<form action="<?php echo base_url(); ?>index.php/Hospital/addTest/<?php echo $appoinmentData->app_id; ?>" role="form" method='post' onmouseover="return form_validate()" name="vform">
<div class="">
<ul class="to_do">
<?php
foreach ($testData as $test) {
echo '
<li>
<p>
'.$test->test_name.' </p>
</br>
<input type="file" class="btn btn-primary" name="'.$test->test_id.'">
</li>
';
}
?>
</ul>
</div>
<input type="submit" class="btn btn-success btn-lg btn-block" value="Update" name="">
</form>
You need multipart/form-data for the rules to be uploaded. Put it back.
Then loop over $_FILES to get all the files that were uploaded.
multipart/form-data MUST be there for file uploads
You can try something like this:
$this->load->library('upload');
$config['upload_path'] = './assets/uploads/'
$config['allowed_types'] = 'jpg|png|jpeg|pdf';
$config['max_size'] = '0';
$config['overwrite'] = TRUE;
$config['encrypt_name'] = TRUE;
$this->upload->initialize($config);
foreach($_FILES as $k => $v)
{
if ($_FILES[$k]['name'] != '')
{
//This do the trick, do_upload need the name of the input
//And in this case, name is the KEY of an array.
if($this->upload->do_upload($k))
{
//Upload Successful
}
}
}

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.

dropzonejs Unable to automatically submit

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

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