how to upload image from codeigniter to mysql - javascript

I am new in CodeIgniter. I am not getting how to update form data in the database. Insertion and showing data from database is done but can't understand how to update data in the database.
I've tried researching this link but data not successfully uploaded.
This is my Controller
//npwp
$temp1 = explode(".", $_FILES['file_npwp']['name']);
$new_name1 = time().'.'.end($temp1);
$config1['upload_path'] = APPPATH.'/file_npwp/';
$config1['file_name'] = $new_name1;
$config1['overwrite'] = TRUE;
$config1['allowed_types'] = 'jpg|jpeg|png|pdf';
$this->load->library('upload',$config1);
$this->upload->initialize($config1);
if(!$this->upload->do_upload('file_npwp')){
$this->data['error'] = $this->upload->display_errors();
}
$media1 = $this->upload->data('file_npwp');
This is my Model
$data_service['file_npwp']= $file_lampiran1;
$data_service['file_ktp']= $file_lampiran2;
$data_service['file_po']= $file_lampiran3;
$data_service['file_registrasi']= $file_lampiran4;
$this->db->where('id_service',$this->input->post('id_service'));
$this->db->update('service_sis', $data_service);
This is my View
<div class="form-group">
<label for="">File NPWP</label>
<input type="file" name="file_npwp" id="file_npwp" class="form-control">
</div>
<br>
<div id="hasilloadfoto"></div>
<br>
<p>*Pastikan semua form sudah terisi dengan benar</p>
<button id="SaveAccount" class="btn btn-success">Simpan</button>
This is my Javascript in my view
$( function() {
var $signupForm = $( '#myForm' );
$signupForm.validate({errorElement: 'em'});
$signupForm.formToWizard({
submitButton: 'SaveAccount',
nextBtnName: 'Selanjutnya',
prevBtnName: 'Sebelumnya',
nextBtnClass: 'btn btn-primary btn-flat next',
prevBtnClass: 'btn btn-default btn-flat prev',
buttonTag: 'button',
validateBeforeNext: function(form, step) {
var stepIsValid = true;
var validator = form.validate();
$(':input', step).each( function(index) {
var xy = validator.element(this);
stepIsValid = stepIsValid && (typeof xy == 'undefined' || xy);
});
return stepIsValid;
},
progress: function (i, count) {
$('#progress-complete).width(''+(i/count*100)+'%');
}
});
});
function filePreview(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#hasilloadfoto + img').remove();
$('#hasilloadfoto').after('<img src="'+e.target.result+'" width="450" height="300"/>');
}
reader.readAsDataURL(input.files[0]);
}
}
$(document).ready(function(){
$("#file_npwp").change(functio () {
filePreview(this);
});
Need help in update operation. I appreciate any help.

you can do in two ways,
You can upload the image to any cloud storage(Aws, Azure, etc) then update the link on your Db
Convert the image into base64 and update it as the string on your DB.
I will prefer to go with step one, I have the sample where I have uploaded it to Azure and update my DB
// This is on Js , Using ajax , I will send to controller
function uploadImage() {
var base_url = '<?php echo BASEURL ?>';
// call ajax to upload image
//event.preventDefault();
var file_data = $('#post-image').prop('files')[0];
var form_data = new FormData();
form_data.append('uploaded_file', file_data);
$.ajax({
url: base_url + "dashboard/uploadImage",
dataType: 'json',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (aData) {
},
error: function (data) {
alert(data);
}
});
}
On Controller ,
public function uploadImage() {
// get the 'api-key' key from Request Headers
$data = array();
if (isset($_FILES ['uploaded_file']['name']) && !empty($_FILES ['uploaded_file']['name'])) {
$userId = $this->input->post("userId");
$file_name = $userId . "_" . uniqid() . ".jpg";
$S3ImgUrl = uploadImageToS3($_FILES ['uploaded_file']['tmp_name'], "app_feed_images", $file_name);
$data = array(
'code' => 555,
'message' => 'Image has been uploaded successfully',
'url' => $S3ImgUrl
);
} else {
$data['code'] = -111;
$msg = "failed to upload image to s3";
$data ['status'] = $this->failed_string;
}
// var_dump($data);
echo json_encode($data);
}
Helper Class
function uploadImageToS3($tmp, $bucket, $file_name) {
$connectionString = "DefaultEndpointsProtocol=https;AccountName=" . azure_bucket_name . ";AccountKey=" . azure_bucket_key;
$blobClient = MicrosoftAzure\Storage\Blob\BlobRestProxy::createBlobService($connectionString);
$containerName = "app-image/" . $bucket;
$containerUrl = "https://hbimg.blob.core.windows.net/";
$content = fopen($tmp, "r");
$options = new MicrosoftAzure\Storage\Blob\Models\CreateBlockBlobOptions();
$content_type = $_FILES['uploaded_file']['type'];
$options->setContentType($content_type);
$blobClient->createBlockBlob($containerName, $file_name, $content, $options);
return $containerUrl . $containerName . "/" . $file_name; }
On the controller side, I have just uploaded the image, you can call you model class with the uploaded image link and update on your DB.
Happy coding :)

All you need is to send the name of the photo in database right then in model you have to add
$this->input->post('databse_column_name')=$variable_name_which_content_file_name

Related

How to add crop image pop up into existing input tag

I wanted to add a crop popup box which crops image into 1:1 ratio, I am using wordpress and created custom form inside a plugin.
Can someone provide me code to add crop modal into my existing code?
I have gone through so many blogs but getting confused in implementing into existing code.
Any help appreciated.
php code for generating input field:
$input_field .= '<input rowid="submission_'.$value->field_id.'" id="uploadImage"
onchange="PreviewImage();" tabindex="'.$indx.'" type="file"
name="matrix_submission_data'.$value->field_id.'" accept="image/png, image/jpeg ,
image/jpeg" class="upload matrix_submission_draft '.$requiredimg.'" >';
$input_field .='<button style="display:none" fieldid='.$value->field_id.'
class="saveimgbtn fileUpload btn btn-primary" style="display: block;float: right;">Save Image</button>';
JQUERY:
jQuery(document).on('click', '.saveimgbtn', function(e){
e.preventDefault();
var fd = new FormData();
var file = jQuery(document).find('input[type="file"]');
var fieldid = jQuery(this).attr('fieldid');
var matrix_id = jQuery("#matrix_id").val();
var userbaseid = jQuery("#userbaseid").val();
fd.append("matrix_id", matrix_id);
fd.append("userbaseid", userbaseid);
fd.append("fieldid", fieldid);
var individual_file = file[0].files[0];
var submission_id = file[0].files[0];
fd.append("file", individual_file);
fd.append('action', 'fiu_upload_file');
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: fd,
contentType: false,
processData: false,
success: function(response){
jQuery('#img_upload,#img_upload_msg').show('slow');
setTimeout(function() {
jQuery('#img_upload,#img_upload_msg').fadeOut('slow');
}, 4000);
jQuery('.saveimgbtn').hide();
jQuery('.hideFileUpload').show();
jQuery('.chooseimagetext').html('<b>Change Image</b>');
}
});
});
PHP:
function fiu_upload_file(){
global $wpdb;
$uploads_dir = ABSPATH.'wp-content/plugins/matrix-engine/includes/submission_images/';
if($_FILES['file']['name']!=""){
$files = $_FILES['file'];
$source = $files['tmp_name'];
$uploadedimage = time().strtolower(str_replace(' ','a',substr($files['name'], -5)));
$destination = trailingslashit( $uploads_dir ) .$uploadedimage;
move_uploaded_file( $source, $destination );
$wpdb->update('wp_matrix_'.$_POST['matrix_id'].'_user_bases',
array(
$_POST['fieldid'] => $uploadedimage,
),array('id'=>$_POST['userbaseid']));
// echo $wpdb->last_query;
echo json_encode(array('message' => 1));
}
exit();
}
add_action('wp_ajax_fiu_upload_file', 'fiu_upload_file');
add_action('wp_ajax_nopriv_fiu_upload_file', 'fiu_upload_file');

How to reload a img attr "src" after ajax call without knowing the file name from the image tag?

I have this html:
<div class="d-inline-flex">
<img id="reloadIMG" class="p-3 mt-5 imgP" onDragStart="return false" <?php echo htmlentities($avatar, \ENT_QUOTES, 'UTF-8', false); ?>>
<input type="file" id="uploadAvatar" name="uploadedAvatar">
</div>
the value of $avatar:
$pathFolderAvatar = 'user/'.$folder.'/avatar/*';
$imgUserPastaAvatar = glob($pathFolderAvatar)[0] ?? NULL;
if(file_exists($imgUserPastaAvatar)){
$avatar = 'src='.$siteURL.'/'.$imgUserPastaAvatar;
}else{
$avatar = 'src='.$siteURL.'/img/avatar/'.$imgPF.'.jpg';
}
and the script to send a ajax call to my file that process the file upload request:
$(function () {
var form;
$('#uploadAvatar').change(function (event) {
form = new FormData();
form.append('uploadedAvatar', event.target.files[0]);
});
$("#uploadAvatar").change(function() {
$("#loadingIMG").show();
var imgEditATTR = $("div.imgP").next().attr("src");
var imgEdit = $("div.imgP").next();
$.ajax({
url: 'http://example/test/profileForm.php',
data: form,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$("#loadingIMG").hide();
$(imgEdit).attr('src', imgEditATTR + '?' + new Date().getTime());
}
});
});
});
i tried to force the browser to reload the img on success ajax call $(imgEdit).attr('src', imgEditATTR + '?' + new Date().getTime()); but the selector from the var imgEdit and imgEditATTR is not working:
console.log(imgEdit); result: w.fn.init [prevObject: w.fn.init(0)]
console.log(imgEdit); result: undefined;
Why is it happening, and how to fix?
I know that there's a bunch of questions about reload img, but on these questions there's not a method to reload a image without knowing the file name. I checked so many questions and this is what the answears say:
d = new Date();
$("#myimg").attr("src", "/myimg.jpg?"+d.getTime());
On my case i don't know the file name, because it's generated randomly on profileForm.php with mt_rand():
$ext = explode('.',$_FILES['uploadedIMG']['name']);
$extension = $ext[1];
$newname = mt_rand(10000, 10000000);
$folderPFFetchFILE = $folderPFFetch.'avatar/'.$newname.'_'.time().'.'.$extension;
//example of the result: 9081341_1546973622.jpg
move_uploaded_file($_FILES['uploadedAvatar']['tmp_name'], $folderPFFetchFILE);
You can return file name in response to your AJAX request and use it in success block to update src attribute of img tag
So your profileForm.php will look something like
$ext = explode('.',$_FILES['uploadedIMG']['name']);
$extension = $ext[1];
$newname = mt_rand(10000, 10000000).'_'.time();
$folderPFFetchFILE = $folderPFFetch.'avatar/'.$newname.'.'.$extension;
//example of the result: 9081341_1546973622.jpg
move_uploaded_file($_FILES['uploadedAvatar']['tmp_name'], $folderPFFetchFILE);
echo $newname // you can also send a JSON object here
// this can be either echo or return depending on how you call the function
and your AJAX code will look like
$.ajax({
url: 'http://example/test/profileForm.php',
data: form,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$("#loadingIMG").hide();
$(imgEdit).attr('src', data);
}
});
Let profileForm.php return the generated filename:
$ext = explode('.',$_FILES['uploadedIMG']['name']);
$extension = $ext[1];
$newname = mt_rand(10000, 10000000);
$folderPFFetchFILE = $folderPFFetch.'avatar/'.$newname.'_'.time().'.'.$extension;
move_uploaded_file($_FILES['uploadedAvatar']['tmp_name'], $folderPFFetchFILE);
echo json_encode(['filename' => $folderPFFetchFILE]);
Then in the callback of your POST request:
success: function (data) {
$("#loadingIMG").hide();
$(imgEdit).attr('src', data.filename);
}

Problem with uploading a image via Ajax Call in php?

I want to upload an image via Ajax call but I am not able to upload the image. Kindly check my code what I am doing wrong:
HTML File:
<input class="form-control" type="file" name="photo1" id="photo1" accept="image/*" onchange="loadFile2(event)">
<button type="button" class="btn btn-secondary btn-lg btn-block" onclick="createDocsVerify()">Update Details</button>
Ajax Call:
<script>
function createDocsVerify () {
var data = {
'photo1' : jQuery('#photo1').val(),
};
//Ajax call Start Here
jQuery.ajax({
url : '/myproject/adminseller/sellerdocsverify.php',
method : 'POST',
data : data,
success : function(data){
if (data != 'passed') {
jQuery('#modal_errors_3').html(data);
}
if (data == 'passed') {
jQuery('#modal_errors_3').html("");
location.reload();
}
},
error : function (){alert("Something went wrong.");},
});
}
</script>
Php File: sellerdocsverify.php
if (isset($_POST['photo1'])) {
$photo1 = sanitize($_POST['photo1']);
// var_dump Output: string(20) "C:\fakepath\0553.jpg"
}
$errors = array();
$required = array(
'photo1' => 'Please select Photo 1',
);
// check if all required fileds are fill out
foreach ($required as $field => $display) {
if (empty($_POST[$field]) || $_POST[$field] == '') {
$errors[] = $display.'.';
}
}
$allowed = array('png', 'jpg', 'jpeg', 'gif');
$photoNameArray = array();
$tmpLoc = array();
$uploadPath = array();
**// Here is the problem**
$name1 = $_FILES['photo1']['name']; // Here is the problem
Var_dump($name1); // OUTPUT: NULL
**// Here is the problem**
$nameArray = explode('.',$name1);
$fileName = $nameArray[0];
$fileExt = $nameArray[1];
$mime = $_FILES['photo1']['type'];
$mimeType = $mime[0];
$mimeExt = $mime[1];
$tmpLoc = $_FILES['photo1']['tmp_name'];
$fileSize = $_FILES['photo1']['size'];
$uploadName = md5(microtime().$j).'.'.$fileExt;
$uploadPath = BASEURL.'images/products/'.$uploadName;
if ($mimeType != 'image') {
$errors[] = 'The file must be an image.';
}
if (!empty($errors)) {
echo display_errors($errors);
}else{
echo 'passed';
// upload file and insert into database
if ($photoCount > 0) {
move_uploaded_file($tmpLoc1, $uploadPath1);
}
$insertSql = "INSERT INTO docTable (`photo1`)
VALUES ('$photo1')";
$db->query($insertSql);
$_SESSION['success_flash'] = '<span style="color:#FFFFFF;text-align:center;">Data Saved Successfully!</span>';
}
?>
Kind check my code and suggest what I am doing wrong, am I doing something wrong in Ajax call or in php, I am getting the value in $photo1.
Any idea or suggestion would be welcome.
You need to do some special "things" to upload files via AJAX. You need to create a FormData object and manually add the file data to it, and also set the contentType, processData and cache options of your AJAX call to false. Your javascript should look like this:
<script>
function createDocsVerify() {
var formdata = new FormData();
var file = jQuery('#photo1').prop('files')[0];
formdata.append('photo1', file);
//Ajax call Start Here
jQuery.ajax({
url: '/myproject/adminseller/sellerdocsverify.php',
method: 'POST',
cache: false,
contentType: false,
processData: false,
data: formdata,
success: function(data) {
if (data != 'passed') {
jQuery('#modal_errors_3').html(data);
}
if (data == 'passed') {
jQuery('#modal_errors_3').html("");
location.reload();
}
},
error: function() {
alert("Something went wrong.");
},
});
}
</script>
That should upload the photo.

dropzone.js edit (add/delete) pre-exisitng image files in Magento

below is my code for deleting images when clicked on "remove file" CTA on the dropzonejs box. However, when the "remove file" is clicked, only the thumbnail image is deleted, and not the actual file.
By calling the delete function in Magento through Ajax when the "removedfile" is called, it should delete the thumbnail as well as the file, but it does not seem to work as the server still keeps the pre-loaded image file.
this.on("removedfile", function(file) {
alert("here");
jQuery.ajax({
url: "<?php echo Mage::getUrl("*/*/deleteimage"); ?>",
type: "POST",
dataType: "json",
data: {'pid': "<?php echo $loadpro->getId(); ?>",'file':file.name},
success: function (data) {
Success = true;//doesnt goes here
},
error: function (textStatus, errorThrown) {
jQuery("#vals").text('');
var det = checkfile('<?php echo $loadpro->getId(); ?>');
if(det != null)
{
maxcount = 1;
}
else {
maxcount = null;
}
}
});
Below is the code for the Magento controller that is called in the function above that listens for the "removedfile."
public function deleteimageAction()
{
$id= $this->getRequest()->getParam('pid');
$imagename= $this->getRequest()->getParam('file');
$product = Mage::getModel('catalog/product')->load($id);
$productMediaConfig = Mage::getModel('catalog/product_media_config');
$mediaGallery = $product->getMediaGalleryImages();
foreach($mediaGallery as $mediagg){
$file = $mediagg->getUrl();
$fileName = basename($file);
if($fileName == $imagename){
$filepath = $mediagg->getFile();
}
}
try{
$storeId=Mage::app()->getStore()->getStoreId();
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$newimage = '';
$data= $this->getRequest()->getParams();
//error_log(print_r($data, TRUE));
$_product = Mage::getModel('catalog/product')->load($data['pid'])->getMediaGalleryImages();
$main = explode('/',$filepath);
foreach($_product as $_image) {
$arr = explode('/',$_image['path']);
if(array_pop($arr) != array_pop($main)){
$newimage = $_image['file'];
$id = $_image['value_id'];
break;
}
}
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$mediaApi->remove($data['pid'],$filepath);
if($newimage){
$objprod=Mage::getModel('catalog/product')->load($data['pid']);
$objprod->setSmallImage($newimage);
$objprod->setImage($newimage);
$objprod->setThumbnail($newimage);
$objprod->save();
}
Mage::app()->setCurrentStore($storeId);
} catch (Exception $e) {
$this->getResponse()->setHeader('Content-type', 'text/html');
$this->getResponse()->setBody('');
}
}
I have tried most of the methods that are in google, as well as stackoverflow, but could not find an answer that works in this case.
If you know a solution to this problem, please let me know.

Codeigniter: Uploading image through Ajax and storing in db

I am using CI 3.0.1 was uploading and inserting image to db successfully before i used ajax, i guess trying to do it with ajax i'm missing something which isn't even sending data to upload maybe because we have to use multipart() in form while in ajax we are just sending data direct to controller, another thing i don't know how to receive the variable in response
my Ajax request function is:
<script type="text/javascript">
$(document).ready(function() {
alert("thirddddddddd");
$('#btnsubmit').click(function()
{
alert("i got submitted");
event.preventDefault();
var userfile = $("input#pfile").val();
alert("uploading");
$.ajax({
url: '<?php echo base_url(); ?>upload/do_upload', //how to receive var here ?
type: 'POST',
cache: false,
data: {userfile: userfile},
success: function(data) {
alert(data);
$('.img_pre').attr('src', "<?php echo base_url().'uploads/' ?>");
$('.dltbtn').hide();
},
error: function(data)
{
console.log("error");
console.log(data);
alert("Error :"+data);
}
});
});
});
And my controller Upload's function do_upload is:
public function do_upload()
{
$config['upload_path'] = './uploads/'; #$this->config->item('base_url').
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('layouts/header');
$this->load->view('home_page', $error);
$this->load->view('layouts/footer');
}
else
{
$data = array('upload_data' => $this->upload->data());
$imagedata = $this->input->post('uerfile');
$session_data = $this->session->userdata('logged_in');
$id = $session_data['id'];
$result = $this->model_edit->update_dp($id, $imagedata);
$image_name = $result->images;
$this->session->set_userdata('image', $image_name);
echo json_encode($name = array('image' => $image_name));
// $image_name = $this->upload->data('file_name');
// $data = array('upload_data' => $this->upload->data());
// redirect("account");
}
}
Now image is not even going to uploads folder, if any other file is needed tell me i'll post it here. Thanks
You cannot send file data using $("input#pfile").val();
var len = $("#pfile").files.length;
var file = new Array();
var formdata = new FormData();
for(i=0;i<len;i++)
{
file[i] = $("input#pfile").files[i];
formdata.append("file"+i, file[i]);
}
and send formdata as data from ajax
Hope it helps !
Try with the below ajax code
var formData = new FormData($('#formid'));
$.ajax({
url: '<?php echo base_url(); ?>upload/do_upload',
data: formData ,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
The file contents may not send through ajax as per your code. Try with the attributes mentioned in above code.

Categories

Resources