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?
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 was working with CodeIgniter php, and using Imagick for some image manipulation. Now I want to upload image and after image manipulation e.g Image equalizing, I want to pass or load the equalized image from controller to view. The image is equalized and uploaded to a path, but I am unable to load the output equalized image to view page. So, kindly guide how to handle this problem?
Controller Code:
class Equalize extends CI_Controller {
public function equalize_image() {
if (isset($_FILES["userfile"])) {
$tmpFile = $_FILES["userfile"]["tmp_name"];
$ext = pathinfo($_FILES["userfile"]["name"], PATHINFO_EXTENSION);
$fileName = uniqid(rand(), true) . "." . $ext;
list($width, $height) = getimagesize($tmpFile);
if ($width == null && $height == null) {
header("Location: index.php");
return;
}
$image = new Imagick($tmpFile);
$image->equalizeImage();
$image->writeImage(FCPATH.'/assets/images' . "/" . $fileName);
header("Content-Type: image/jpeg");
echo $image;
}
}
}
View Code:
<label>Input Image</label>
<form method="post" id="upload_form" enctype="multipart/form-data">
<input type='file' name="userfile" size="20" onchange="readURL(this);"/>
<label>Orignal Image</label><br>
<img id="blah" src="#" alt="" />
<label>Equalized Image </label>
<div id="result">
</div>
<input type="submit" name="upload" id="upload" value="Apply" class="btn btn-info" />
</form>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.width(200)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
$(document).ready(function(){
$('#upload_form').on('submit', function(e){
e.preventDefault();
if($('#userfile').val() == '')
{
alert("Please Select the File");
}
else
{
$.ajax({
url:"<?php echo base_url(); ?>Equalize/equalize_image",
//base_url() = http://localhost/tutorial/codeigniter
method:"POST",
data:new FormData(this),
contentType: false,
cache: false,
processData:false,
success:function(data)
{
$('#result').html(data);
}
});
}
});
});
</script>
</body>
With this code I am facing this output: https://imgur.com/85vMove. How to load the image in view?
Take 1
Just pass the newly created image url to the ajax success function via json and modify the img src to that url.
HTML:
<label>Input Image</label>
<form method="post" id="upload_form" enctype="multipart/form-data">
<input type='file' name="userfile" size="20" onchange="readURL(this);"/>
<label>Orignal Image</label><br>
<img id="blah" src="#" alt="" />
<label>Equalized Image </label>
<div id="result">
<img src="http://via.placeholder.com/300x400">
</div>
<input type="submit" name="upload" id="upload" value="Apply" class="btn btn-info" />
</form>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.width(200)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
$(document).ready(function () {
$('#upload_form').on('submit', function (e) {
e.preventDefault();
if ($('#userfile').val() == '')
{
alert("Please Select the File");
} else
{
$.ajax({
url: "<?php echo base_url(); ?>Equalize/equalize_image",
method: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
dataType: 'json',
success: function (data)
{
if (data.success == true) {
$('#result').find('img').attr('src', data.file);
} else {
alert(data.msg);
}
}
});
}
});
});
</script>
</body>
PHP:
try {
if (!isset($_FILES["userfile"])) {
throw new Exception('No file uploaded.');
}
$tmpFile = $_FILES["userfile"]["tmp_name"];
$ext = pathinfo($_FILES["userfile"]["name"], PATHINFO_EXTENSION);
$fileName = uniqid(rand(), true) . "." . $ext;
list($width, $height) = getimagesize($tmpFile);
if ($width == null && $height == null) {
throw new Exception('An error occured.');
}
$image = new Imagick($tmpFile);
$new_file = "assets/images/{$fileName}";
$image->equalizeImage();
$image->writeImage(FCPATH . '/' . $new_file);
echo json_encode(array('success' => true, 'file' => base_url($new_file)));
} catch (Exception $e) {
echo json_encode(array('success' => false, 'msg' => $e->getMessage()));
}
Take 2
This is the only way you can download the file without having it saved on the server.
class Test extends CI_Controller {
public function index() {
$this->load->view('test');
}
public function eq() {
try {
if (!isset($_FILES['userfile'])) {
throw new Exception('No file uploaded.');
}
$file_error = $_FILES['userfile']['error'];
if ($file_error !== 0) {
throw new Exception('Error uploading: Code ' . $file_error);
}
$tmp_file = $_FILES['userfile']['tmp_name'];
list($width, $height) = getimagesize($tmp_file);
if ($width == null && $height == null) {
throw new Exception('An error occured.');
}
$image = new Imagick($tmp_file);
$image->equalizeImage();
$encoded_file = base64_encode($image->getimageblob());
echo json_encode(array('success' => true, 'type' => $image->getimageformat(), 'file' => $encoded_file));
} catch (Exception $e) {
echo json_encode(array('success' => false, 'msg' => $e->getMessage()));
}
}
public function download() {
$contents = $this->input->post('image_contents');
$extension = $this->input->post('extension');
if (is_null($contents) || is_null($extension)) {
show_error('Image contents empty');
}
$name = 'equalized_image.' . strtolower($extension);
$contents = base64_decode($contents);
$this->load->helper('download');
force_download($name, $contents);
}
}
HTML:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#original-image')
.attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
$(document).ready(function () {
$('#download').hide();
$('#upload_form').on('submit', function (e) {
e.preventDefault();
if ($('#userfile').val() == '')
{
alert("Please Select the File");
} else
{
$.ajax({
url: "/neou_cms/test/eq",
method: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
dataType: 'json',
success: function (data)
{
console.log(data);
if (data.success == true) {
var image_content = 'data:image/' + data.type + ';base64,' + data.file;
$('#eq-image').attr('src', image_content);
$('#image_contents').attr('value', data.file);
$('#extension').attr('value', data.type);
$('#download').show();
} else {
alert(data.msg);
}
}
});
}
});
});
</script>
</head>
<body>
<form method="post" id="upload_form" enctype="multipart/form-data">
<table border="1">
<tr>
<td colspan="2"><input type="file" name="userfile" size="20" onchange="readURL(this);"></td>
</tr>
<tr>
<td>Original Image</td>
<td>Equalized Image</td>
</tr>
<tr>
<td>
<img id="original-image" src="http://via.placeholder.com/300x400" width="300" height="auto">
</td>
<td>
<img id="eq-image" src="http://via.placeholder.com/300x400" width="300" height="auto">
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="upload" id="upload" value="Apply" class="btn btn-info">
</td>
</tr>
</table>
</form>
<form method="post" action="/neou_cms/test/download">
<input type="hidden" value="" name="image_contents" id="image_contents">
<input type="hidden" value="" name="extension" id="extension">
<input type="submit" name="download" id="download" value="Download Image">
</form>
</body>
</html>
here in ajax script input with id name'file' is fine i want data from input with id 'vid' also sent using ajax how to later below code
<input type="file" name="file" id="file" />
<div style="background:url() no-repeat">
<span id="uploaded_image" ><img src=" '.$row["carimg"].' " height="150" width="225" class="img-thumbnail" /></span></div>
here is the ajax code
<script>
$(document).ready(function(){
$(document).on('change', '#file', function(){
var name = document.getElementById("file").files[0]...
var form_data = new FormData();
var ext = name.split('.').pop().toLowerCase();
if(jQuery.inArray(ext, ['gif','png','jpg','jpeg']) == -1)
{
alert("Invalid Image File");
}
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getEleme...
var f = document.getElementById("file").files[0]...
var fsize = f.size||f.fileSize;
if(fsize > 2000000)
{
alert("Image File Size is very big");
}
else
{
form_data.append("file", document.getElementById('file').files[0]...
$.ajax({
url:"up1.php",
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
beforeSend:function(){
$('#uploaded_image').html("<label class='text-success'>Image Uploading...</label>");
},
success:function(data)
{
$('#uploaded_image').html(data);
}
});
}
});
});
</script>
here is the php
<?php
//upload.php
$id = $_FILES["vid"];
if($_FILES["file"]["name"] != '')
{
$test = explode('.', $_FILES["file"]["name"]);
$ext = end($test);
$name = gen_random_string(6)."n" . '.' . $ext;
$location = 'assets/img/cars/' . $name;
move_uploaded_file($_FILES["file"]["tmp_name"], $location);
echo $id;
echo '<img src="'.$location.'" height="150" width="225" class="img-thumbnail" />';
$sql = "UPDATE vehicles SET carimg='".$location."' WHERE vid='".$id."'";
}
mysqli_query($connect, $sql);
?>
How to send more than one data in this php ajax form this one capable of sending one data only please help
Add below form_data.append("file", document.getElementById('file').files[0]
this statement
form_data.append("vid",document.getElementById('vid').innerHTML);
Since you are POSTing, so from your php file:
$vid = $_POST['vid'];
I have an html form where i have input file array. What im trying to achieve is get the file array in php file loop through it and check if a file extension is correct else add it to array and then show as json array in ajax. Can someone help me? here is the code for the form:
<html>
<head>
<title>Multiple file upload handling</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#form").submit(function(e){
var file1 = $("#file1").val();
var file2 = $("#file2").val();
$("#results").text("");
var results = $("#results");
if(file1 == "" || file2 == ""){
results.text("File 1 and File 2 are empty.");
}else {
var formarray = new FormData($("#form")[0]);
$.ajax({
url: "upload.php",
type: "POST",
dataType: "JSON",
enctype: 'multipart/form-data',
async: false,
cache: false,
contentType: false,
processData: false,
data: formarray,
success:function(response){
if(response.success == false){
$(response.message).each(function(index, value){
results.append("<li id="+ index + ">" + value + "</li>");
});
}else{
alert(response.message);
}
}
});
}
e.preventDefault();
});
})
</script>
</head>
<body>
<form method="post" role="form" enctype="multipart/form-data" id="form">
<input type="file" id="file1" name="file[]" style="margin-bottom:30px;"><br>
<input type="file" id="file2" name="file[]" style="margin-bottom:30px;"><br>
<input type="submit" id="upload" name="upload">
</form>
<div id="results"></div>
</body>
</html>
And below is the php code:
<?php
$filenames = $_FILES['file']['name'];
$filesizes = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
$data = array();
$errors = array();
foreach($filenames as $key=>$value){
$filesize = $_FILES["file"]["size"][$key];
$filetype = $_FILES["file"]["type"][$key];
$file_tmpname = $_FILES["file"]["tmp_name"][$key];
$valid_extensions = array("jpeg", "jpg", "gif", "png");
$ext = explode(".", $value);
$extension = end($ext);
if(!in_array($extension, $valid_extensions)){
$errors[] = $value;
$data["success"] = false;
$data["message"] = $errors;
} else {
$data["success"] = true;
$data["message"] = "success";
move_uploaded_file($file_tmpname, "uploads/".$filename);
}
}
echo json_encode($data);
?>
Am trying to upload an image to images folder using ajax but its not working
when i choose an image then the image should upload to my folder in local hard drive and further i will use that.
Please help me
My Code is :
SCRIPT
$(document).ready(function() {
$('#pathAbout,#path,#pathWork').change(function(){
if($(this).val() !=""){
$.ajax({
type: "POST",
url: "imageLoad.php",
data: "name = <?php echo $_FILES['imgPath']['name']; ?>&type=<?php echo $_FILES['imgPath']['type']; ?>&tmp_name=<?php echo $_FILES['imgPath']['tmp_name']; ?>",
success: function(msg){
alert(msg);
}
});
}
});
});
</script>
HTML
<form method="POST" action="tabs.php?page=HOME" enctype="multipart/form-data">
<table>
<tr>
<td><label>Choose Image</label></td>
<td><input type="file" id ="pathAbout" name="imgPath" /></td>
</tr>
</table>
</form>
PHP
if(!empty($_POST)) {
if((isset($_POST['name']) && $_POST['name'] != '') || (isset($_POST['type']) && $_POST['type'] != '') ||(isset($_POST['tmp_name']) && $_POST['tmp_name'] != ''))
{
$name = $_POST['name'];
$type = $_POST['type'];
$tmp_name = $_POST['tmp_name'];
$extension = strtolower(substr($name, strpos($name , '.') +1));
if(($extension == 'png' || $extension == 'jpeg' || $extension == "jpg")&&($type == "image/png" || $type == "image/jpeg" || $type == "image/jpg"))
{
$location = 'images/';
if(move_uploaded_file($tmp_name,$location."$name"))
{
echo "Loaded";
} else {
echo "Error occured";
}
} else {
echo "Unsupported file format";
}
} else {
echo "Please choose a file";
}
} else {
echo "No Information found";
}
This is my code but nothing is happening when i choose a file
If you want you can use Uploadify here you can also see demo and for sample code for eg-
$(function() {
$("#file_upload").uploadify({
'formData' : {'someKey' : 'someValue', 'someOtherKey' : 1},
'swf' : '/uploadify/uploadify.swf',
'uploader' : '/uploadify/uploadify.php',
'onUploadStart' : function(file) {
$("#file_upload").uploadify("settings", "someOtherKey", 2);
}
});
});
$("#image_upload2").uploadify(uploadifyBasicSettingsObj);
uploadifyBasicSettingsObj.onUploadSuccess = function(file, data, response)
{
$('.tempImageContainer2').find('.uploadify-overlay').show();
/* Here you actually show your uploaded image.In my case im showing in Div */
$('.tempImageContainer2').attr('style','background- image:url("../resources/temp/thumbnail/'+data+'")');
$('#hidden_img_value2').attr('value',data);
}
The HTML code:
<div class="boxWrapper tempImageContainer2" data-image-container-id="2">
<input type="file" accept="gif|jpg" name="image2" style="" id="image_upload2"/>
<input type="hidden" value="" name="image[]" id="hidden_img_value2">
<input type="hidden" name="upload_path" value="" id="upload_path2" class="upload_path">
<div class="uploadify-overlay">Change</div>
<a class="remove-pic-link" href="javascript:void(0)" style="display:none">Remove</a>
</div>
It is not possible to upload an image directly using AJAX, but there are some libraries that create dynamic iframes to accomplish this.
Check out this one, which I have used in several projects: valums.com/ajax-upload. It even comes with example serverside code for several PHP application frameworks.
You can't upload file using AJAX , you need to use a trick consisting a 'iframe' and the web form , also some javascript.
This link may help you.
HTML
<div class="field">
<label class="w15 left" for="txtURL">Logo:</label>
<img id="logoPreview" width="150px" height="150px" src='default.jpg' />
<input class="w60" type="file" name="txtURL" id="txtURL" />
</div>
JQuery
$('#txtURL').on('change', function(){
$.ajaxFileUpload({
type : "POST",
url : "ajax/uploadImage",
dataType : "json",
fileElementId: 'txtURL',
data : {'title':'Image Uploading'},
success : function(data){
$('#logoPreview').attr('src', data['path']);
},
error : function(data, status, e){
alert(e);
}
});
});
Ajax controller:
public function uploadImage()
{
$status = "";
$msg = "";
$filename='';
$file_element_name = 'txtURL';//Name of input field
if (empty($_POST['title'])){
$status = "error";
$msg = "Please enter a title";
}
if ($status != "error"){
$targetPath = ''.date('Y').'/'.date('m').'/';
if(!file_exists(str_replace('//','/',$targetPath))){
mkdir(str_replace('//','/',$targetPath), 0777, true);
}
$config['upload_path'] = $targetPath;
$config['allowed_types'] = 'jpg|png|jpeg';
$config['max_size'] = 150000;
$config['file_name']=time(); //File name you want
$config['encrypt_name'] = FALSE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if(!$this->upload->do_upload($file_element_name)){
$status = 'error';
$msg = $this->upload->display_errors('', '');
}
else{
$data = $this->upload->data();
$filename = $targetPath.$data['file_name'];
}
//#unlink($_FILES[$file_element_name]);
}
echo json_encode(array('status' => $status, 'msg' => $msg,'path'=>$filename));
}
Add Ajaxfileupload.js
You can't upload an image directly using AJAX
The answer is in response to this:
data: "name = <?php echo $_FILES['imgPath']['name']; ?>&type=<?php echo $_FILES['imgPath']['type']; ?>&tmp_name=<?php echo $_FILES['imgPath']['tmp_name']; ?>",