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.
Related
I am trying to upload a csv file using this code but the file directory is not getting uploaded to the folder and i cannot see any error in the code.
Please help me in this.
HTML code:
<form method="POST" action="submit.php" enctype="multipart/form-data"">
<input type="file" name="file" id="upload"><br>
</form>
JQUERY AJAX code:
$(document).ready(function(){
$('#upload').on('change', function(e) {
e.preventDefault();
var file=this.files[0];
console.log(file);
var filename = file.name;
var ext = filename.split('.')[1];
if(ext == "csv"){
FileUploadAjaxCall();
}else{
$("#fileMsg").html("Extension not valid:Try Again");
}
});
});
function FileUploadAjaxCall(){
$.ajax({
url:'submit.php',
type:'POST',
data:new FormData($('#upload').get(0)),
contentType:false,
cache:false,
processData:false,
success:function(data){
if(data == 1){
console.log("File Uploaded Successfully");
}else{
console.log(data);
console.log("Error");
}
}
});
}`
PHP code:
<?php
$file = $_FILES['file'];
$filename = $_FILES['file']['name'];
$filetmpname = $_FILES['file']['tmp_name'];
$fileDes = 'uploads/'.$filename;
$t = move_uploaded_file($filetmpname,$fileDes);
if($t == true){
echo 1;
};
?>
I have re-written your code as follows. Its always good to validate files upload at server backend and javascript validation can be fooled.
Try the code below and let me see what happens
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload_processor.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer").html(data);
$("#errorLayer").html(data);
},
error: function()
{
}
});
}));
});
</script>
</head>
<body>
<div>
<form id="uploadForm" action="upload_processor.php" method="post">
<div id="targetLayer"></div>
<div id="errorLayer"></div>
<div id="uploadFormLayer">
<input name="file" type="file" class="inputFile" /><br/>
<input type="submit" value="Submit" class="btnSubmit" />
</form>
</div>
</div>
</body>
</html>
<?php
if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['file']['tmp_name'])) {
$fileName = $_FILES['file']['name'];
$sourcePath = $_FILES['file']['tmp_name'];
$targetPath = "uploads/".$_FILES['file']['name'];
if($fileName ==''){
echo "<div id='errorLayer'>Please select file</div>";
exit;
}
$fileType = pathinfo($fileName, PATHINFO_EXTENSION);
$allowTypes = array('csv');
if (!in_array($fileType, $allowTypes, true)) {
echo "<div id='errorLayer'>File type is invalid. Only CSV is allowed</div>";
exit;
}
if(move_uploaded_file($sourcePath,$targetPath)) {
echo "<div id='targetLayer'>File uploaded successfully</div>";
?>
<?php
}
}
}
?>
//form.html
<form method="POST" action="submit.php" id="uploadForm">
<input type="file" name="file" id="upload" accept=".csv"><br>
<input type="submit">
</form>
<div id="fileMsg"></div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function(e){
$('#uploadForm').on('submit', function(e) {
e.preventDefault();
$.ajax({
url:'submit.php',
type:'POST',
data:new FormData(this),
contentType:false,
cache:false,
processData:false,
success:function(){
$("#fileMsg").html("File Uploaded Successfully");
},
error:function(){
//$("#fileMsg").html(data);
$("#fileMsg").html("Error");
}
});
});
});
</script>
//submit.php
<?php
// $file = $_FILES['file'];
$filename = $_FILES["file"]["name"];
$filetmpname = $_FILES["file"]["tmp_name"];
$fileDes = "uploads/".$filename;
$t = move_uploaded_file($filetmpname,$fileDes);
if($t == true){
echo "1";
};
?>
u can do it like this
I wanna update profile picture of user that has logged in to my website.
I use ajax, jquery, php to update data, in order to update data without refresh the page.
This code just working to upload image into folder, but when I use this code to update image from database, it only sent null into database.
jquery and ajax script
$("#form-ava").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "../config.inc/upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function()
{
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data)
{
if(data=='invalid')
{
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
}
else
{
// view uploaded file.
$("#preview-ava").html(data).fadeIn();
$("#form-ava")[0].reset();
$("#hidden-list").hide();
}
},
error: function(e)
{
$("#err").html(e).fadeIn();
}
});
}));
And it's the php syntax
upload.php
<?php
require_once 'koneksi.php';
if($_POST)
{
$id_user= $_POST['id_user'];
$img = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp'); // valid extensions
$path = '../images/ava/'; // upload directory
try {
// get uploaded file's extension
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
// can upload same image using rand function
$final_image = rand(1000,1000000).$img;
// check's valid format
if(in_array($ext, $valid_extensions))
{
$path = $path.strtolower($final_image);
if(move_uploaded_file($tmp,$path))
{
echo "<img src='$path' />";
}
else
{
echo 'invalid';
}
$update = $db_con->prepare("UPDATE tb_users SET image=:img WHERE id_user=:id_user");
$update->bindparam(":id_user", $id_user);
$update->bindparam(":img", $image);
$update->execute();
$count = $update->rowCount();
if($count>0) {
echo "success";
}else {
echo "can't update!";
}
}
}catch(PDOException $e) {
echo $e->getMessage();
}
}
?>
HTML syntax
<form id="form-ava" action="../config.inc/upload.php" method="post" enctype="multipart/form-data">
<input type="hidden" id="id_user" name="id_user" value="<?php echo $row->id_user;?>">
<input id="ava-img" type="file" name="image" value="<?php echo $row->image;?>"/>
<input id="button" type="submit" value="Simpan" name="update"></br>
</i> Batal
</form>
<div id="err"></div>
<form id="form-ava" action="../config.inc/upload.php" method="post" enctype="multipart/form-data">
<input type="hidden" id="id_user" name="id_user" value="<?php echo $row->id_user;?>">
<input id="ava-img" type="file" name="image" value="<?php echo $row->image;?>"/>
<input id="button" type="submit" value="Simpan" name="update"></br>
</i> Batal
</form>
<div id="err"></div>
<script type="text/javascript">
$("#form-ava").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "../config.inc/upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function()
{
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data)
{
if(data=='invalid')
{
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
}
else
{
// view uploaded file.
$("#preview-ava").html(data).fadeIn();
$("#form-ava")[0].reset();
$("#hidden-list").hide();
}
},
error: function(e)
{
$("#err").html(e).fadeIn();
}
});
}));
</script>
I found two errors in your code in proses.php
<?php include 'koneksi.php';
$foto = #$_POST['foto'];
$id = #$_POST['id'];
$update = $db->prepare("UPDATE tb_users SET foto=:foto WHERE id=:id");
$update>bindParam(":id", $id);
$update->bindParam(":foto", $foto);
$update->execute();
if($update->rowCount() > 0) {
echo "success";
}
?>
the error messages would be very helpful, but at the very least you are missing a - in $update>bindParam(":id", $id);, so it should be $update->bindParam(":id", $id);
you did the same thing again with $update>rowCount() should be $update->rowCount()
update: I see you edited your question to fix those, but still haven't posted the errors you're receiving. Were those tpyos in your question, or are you progressively fixing your code?
still, it looks like you're missing a closing curly brace } in this statement:
if($update>rowCount() > 0) {
echo "success";
?>
also, why are you silencing notices with #$_POST? if those values are empty, then do you really want to be updating the table?
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);
}
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?
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