Codeigniter do_upload method is not working - javascript

I am working on a cms with Codeigniter. I am trying to upload file from system. I am receiving the file but the do_upload method is not working. There are similar questions on this topic, but none of the answers of them worked.
Here is my method:
public function fileupdate($productId=False){
$formData = $this->input->post();
if (isset($formData['activityNewFile'])) {
foreach ($formData['activityNewFile'] as $key => $value) {
$rndNumber = rand(1,500);
$fileLastName = sef_url($formData['activitynewfilename'.$value]);
// Set preference
$config['upload_path'] = '../assets/';
$config['allowed_types'] = 'pdf|doc|docx|xls|xlsx';
$config['max_size'] = '80960'; // max_size in kb
$config['file_name'] = $fileLastName;
$upFile = 'activitynewfile'.$value;
// Load upload library
$this->load->library('upload',$config);
// File upload
if($this->upload->do_upload($upFile)){
// Get data about the file
$uploadData = $this->upload->data();
$filename = $uploadData['file_name'];
$daData = array(
'productId' => $productId,
'productFileName' => $formData['activitynewfilename'.$value],
'productFile' => $filename
);
$productfileInsert = $this->db->insert('productfile',$daData);
}
}
}
$this->success("İşlem tamamlandı.");
}
HTML part:
<form class="m-form m-form--fit m-form--label-align-right" role="form" method="POST" id="product_file_edit" action="<?=base_url('product/product/fileupdate/'.$productInfo->productId);?>" enctype="multipart/form-data" onsubmit="return false; form_gonder('product_file_edit')" >
<div class="modal-body">
<div class="form-group m-form__group row">
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="col-md-12" style="margin-bottom: 10px;padding: 0;" id="file_row">
<button onclick="addFileRow('file_add')" class="btn btn-primary btn-sm">
<i class="zmdi zmdi-plus"></i> Add
</button>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button onclick="form_gonder('product_file_edit')" class="btn btn-green btn-sm">
Save
</button>
</div>
</form>
Javascript part:
function addFileRow(tur){
if(tur=="file_add"){
emreFile = Math.floor(Math.random() * 10);
myhtmlFile = '<div class="col-md-12 row" id="filenew'+emreFile+'" style="padding: 0;margin: 0;margin-bottom: 10px;"><div class="input-group"><input type="hidden" name="activityNewFile[]" value="'+emreFile+'"><img src="../assets/file/pdfword.png" style="width: 38px;float: left;height: 38px;"><input type="text" name="activitynewfilename'+emreFile+'" class="form-control" placeholder="Dosya Adı" style="width: 45%;float: left;height: 39px;"><input type="file" name="activitynewfile'+emreFile+'" accept=".xls,.xlsx,.doc,.docx,.pdf" class="form-control" placeholder="Dosya Adı" style="width: 46%;opacity: 1;float: right;position: relative;"><span class="input-group-btn"><button class="btn btn-red btn-fab btn-fab-sm animate-fab" onclick="deleteNewFileRow('+emreFile+')" type="button"><i class="zmdi zmdi-delete"></i></button></span></div></div>';
var icerikFile = myhtmlFile;
jQuery("#file_row").prepend(icerikFile);
}
}
I would be very grateful if you could find out what the problem is.

Your problem is actually the file is not loading properly. There is no error in your codes. Make sure file_uploads is turned on on your server. Make sure the upload_max_filesize value is not smaller than your file size.

Related

JsTree submit form when a node is selected

I am using JsTree to create a tree structure to display folder hierarchical order.
What I want to do is, when the user selects a node and move button is clicked, a form will be submitted.
<?php
echo $this->Form->create("MediaDirectory", ['type' => 'post', 'class' => 'form-horizontal','autocomplete' => "off",'novalidate' => "novalidate"]);
?>
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label class="col-4 col-form-label">Testing</label>
<div class="col-8">
<?php
$folderData = $hah;
$folders_arr = array();
foreach($folderData as $row)
{
$parentid = $row['MediaDirectory']['parent_id'];
if($parentid == null) $parentid = "#";
$folders_arr[] = array(
"id" => $row['MediaDirectory']['id'],
"parent" => $parentid,
"text" => $row['MediaDirectory']['name'],
);
}
?>
<div id="folder_jstree"></div>
<textarea id='txt_folderjsondata' hidden><?= json_encode($folders_arr) ?></textarea>
</div>
</div>
</div>
</div>
<button type="button" name="cancel" class="btn btn-secondary btn-rounded btn-bordered waves-effect" onclick="window.history.back();">Cancel</button>
<button type="submit" name="submit" class="btn btn-primary btn-rounded waves-effect waves-light">Move</button>
<?php echo $this->Form->end(); ?>
Script
<script type="text/javascript">
$(document).ready(function(){
var folder_jsondata = JSON.parse($('#txt_folderjsondata').val());
$('#folder_jstree').jstree({ 'core' : {
'data' : folder_jsondata,
'multiple': false
} });
});
</script>
I don't have any experience expereience with Javascript and JsTree. Can someone help me.

Upload or Draw Signature on Laravel form

I used this https://www.itsolutionstuff.com/post/laravel-signature-pad-example-tutorialexample.html to create a signature pad. I am looking for a way to add an option to upload a signature or use the pad to draw a signature.
Here's what I wrote:
Laravel Blade Code
<form method="POST" action="{{ route('signaturepad.upload') }}">
<div class="tab-content">
<div class="tab-pane fade show active" id="draw">
<div class="col-md-12">
<label class="" for="">Draw Signature:</label>
<br/>
<div id="sig"></div>
<br><br>
<button id="clear" class="btn btn-danger">Clear Signature</button>
{{--<button class="btn btn-success">Save</button>--}}
<textarea id="signature" name="signature" style="display: none"></textarea>
</div>
</div>
<div class="tab-pane fade" id="upload">
<label class="" for="">Upload Signature:</label>
{{--<div class="form-group"></div>
<input type="file" name="file" id="file" required>--}}
{{--<button type="submit">Submit</button>--}}
</div>
<button class="btn btn-success">Save</button>
</div>
</form>
Javascript
<script src="{{ asset('js/pages/jquery.signature.js')}}"></script>
<script type="text/javascript">
var sig = $('#sig').signature({syncField: '#signature', syncFormat: 'PNG'});
$('#clear').click(function(e) {
e.preventDefault();
sig.signature('clear');
$("#signature").val('');
});
</script>
Controller
if(!empty($request->input('signature')) || (!empty($request->input('file')))) {
echo $request->signature;
echo $request->file;
dd('passed');
//$folderPath = public_path('uploads/');
//$data_uri = $request->signature;
//$encoded_image = explode(",", $data_uri)[1];
//$decoded_image = base64_decode($encoded_image);
//$file = $folderPath . uniqid();
//file_put_contents($file, $decoded_image);
return view('dashboard');
} else {
//dd('Signature is empty.');
return back()->withErrors(['msg', 'Signature Empty']);
}
Drawing the Signature works when one of the file uploads is commented out. When both are active they don't post and both don't work. My question is how do I work with both where one can either draw or upload the signature. I have tried if statements in the controller to no avail.
Thanks in Advance!

Uploaded image is not returned to PHP

I am trying to make a form for editing a product but if I upload a image the image can not be found by my PHP code it throws this error:
Notice: Undefined index: image in C:\xampp\htdocs\pages\shopmanager\admin\producteditor.php on line 10
Notice: Undefined index: image in
C:\xampp\htdocs\pages\shopmanager\admin\producteditor.php on line 11
Upload failed
This is my Code:
$db = new Database;
$product = mysqli_fetch_array($db->db_query("SELECT * FROM product WHERE ID = '" . $_GET['id'] . "'"));
$image = mysqli_fetch_array($db->db_query("SELECT name,src FROM images WHERE id =".$product['image-id']));
$category = $db->db_query("SELECT * FROM category");
$productcat = mysqli_fetch_array($db->db_query("SELECT `cat-id` FROM `category-product` WHERE `prod-id` = ".$product['ID']));
if(isset($_POST['submit'])){
$uploaddir = '/../../../src/images/';
$uploadfile = $uploaddir . basename($_FILES['image']['name']);
if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
}
?>
<!--page content-->
<div class="col-9">
<div style="background-color:#c6c8ca !important; color:black" class="jumbotron">
<div class="container">
<form class="well form-horizontal" action="producteditor.php?id=<?= $_GET['id'] ?>" method="post"
id="producteditor_form">
<fieldset>
<!-- Upload image input-->
<input id="upload" name="image" type="file" onchange="readURL(this);"
class="form-control border-0" accept="image/*" hidden>
<div class="input-group-append">
<label for="upload" class="btn btn-light m-0 rounded-pill px-4"> <i
class="fa fa-cloud-upload mr-2 text-muted"></i><small
class="text-uppercase font-weight-bold text-muted"> Kies
bestand</small></label>
</div>
<!-- Uploaded image area-->
<div class="image-area mt-4"><img id="imageResult"
src="../../../<?=$image['src']?>" alt="<?=$image['name']?>"
class="img-fluid rounded shadow-sm mx-auto d-block">
</div>
</div>
</div>
</div>
<!-- Button -->
<div class="form-group">
<div class="text-center">
<button class="btn btn-lg btn-success form-spacing-top"
name="submit">Opslaan</button>
</div>
</div>
</fieldset>
</form>
</div>
</div><!-- /.container -->
</div>
</div>
<div class="col"></div>
</div>
</div>
<script>
/* ==========================================
SHOW UPLOADED IMAGE
* ========================================== */
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#imageResult')
.attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
$(function() {
$('#upload').on('change', function() {
readURL(input);
fetch(url, {
method: 'POST',
body: readURL(input)
});
});
});
/* ==========================================
SHOW UPLOADED IMAGE NAME
* ========================================== */
var input = document.getElementById('upload');
var infoArea = document.getElementById('upload-label');
input.addEventListener('change', showFileName);
function showFileName(event) {
var input = event.srcElement;
var fileName = input.files[0].name;
infoArea.textContent = 'File name: ' + fileName;
}
</script>
Your <form> needs to have the enctype='multipart/form-data' attribute.
See: What does enctype='multipart/form-data' mean?

Ajax file upload in PHP using javascript popup [duplicate]

This question already has answers here:
jQuery Ajax File Upload
(27 answers)
Closed 3 years ago.
I am having problem with uploading file with JavaScript Popup. This is my first experience to upload file with such JavaScript popup. I don't know how to pass the input[type:file] to the ajax function and then send to the php file for uploading.
This is the button which calls the popup:
<a class="btn btn-primary btn-sm" data-toggle="modal" data-target="#uploadDocument">Upload Document</a>
<div class="modal fade" id="uploadDocument" role="dialog">
<div class="modal-dialog" style="top: 20%;">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header" style="background-color: #367FA9">
<h4 class="modal-title" id="myModalLabel" style="color:white">Upload Document</h4>
</div>
<!-- Modal Body -->
<div class="modal-body" style="padding-top: 20px; padding-right: 40px; padding-left: 40px;">
<!-- <img src="police/images/new.jpg" width="120px" height="100px"> -->
<p id="uploadMD"></p>
<form role="form" id="uploadForm" >
<div class="form-group">
<input type="hidden" name="" id="rowid" value="<?php echo $id; ?>">
</div>
<div class="form-group">
<label>Document Name</label>
<input type="text" name="" id="documentName" class="form-control">
</div>
<div class="form-group">
<label>Document</label>
<input type="file" class="form-control" placeholder="Please Select File" id="documentFile">
</div>
<div class="form-group text-center">
<button type="button" class="btn btn-primary submitBtn block" style="background-color: #367FA9" onclick="uploadDocument()" style="width: 100%;">Upload Document</button>
</div>
</form>
</div>
<!-- Modal Footer -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The javascript code is as follows:
<script>
function uploadDocument(){
var rowid = $('#rowid').val();
var documentName = $('#documentName').val();
var documentFile = $('#documentFile').val();
if(documentName.trim() == '' ){
alert('Please write file name');
$('#documentName').focus();
return false;
}else if(documentFile.trim() == '' ){
alert('Please Select File');
$('#documentFile').focus();
return false;
}else {
$.ajax({
method:'POST',
url:'upload.php',
enctype: 'multipart/form-data',
data:'&rowid='+rowid+'&documentName='+documentName+'&documentFile='+documentFile,
success: function(result){
$('#uploadForm').trigger('reset');
if(result == '1'){
$('#uploadMD').html('<span style="color:green;">Your File is uploaded. Thank you</span>');
setTimeout(function(){ window.location.reload() }, 5000);
}
else{
$('#uploadMD').html('<span style="color:red;">Uploading Problem</span>').fadeIn().delay(5000).fadeOut();
}
}
});
}
}
</script>
and the upload.php file is here:
<?php
$rowid = $_POST['rowid'];
$documentName = $_POST['documentName'];
$file_name = $_FILES['documentFile']['name'];
$file_move = move_uploaded_file($file_tmp,"../uploads/ps/".$file_name);
include "../include/configs.php";
if ($file_move) {
$q2 = "UPDATE requests SET support_doc='$file_name' WHERE slug='$id'";
$query = mysqli_query($con, $q2);
if ($query) {
echo $success = 1;
}
}
?>
Thanks in advance.
Try formdata to pass in php file ajax call
var formData = new FormData();
formData.append('section', 'general');
formData.append('action', 'previewImg');
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'Your url here',
data: formData,
type: 'POST',
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
// ... Other options like success and etc
});
Thanks

I can't reset input file inside form after submit

I have a form with some fields and after submit finish i want to reset whole form but only reset input text areas not input type file.
I check every similar questions and solutions but none of them work for me.Some solutions refresh page which i don't want that.
<form class=" dropzone px-5" id="mydropzone">
<h2 class="text-center">Lets create your menu</h2>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputCalories">Calorie</label>
<input type="text" class="form-control" id="inputCalories" required>
</div>
<div class="form-group col-md-6">
<label for="cc">Calorie Calculator</label>
<button id="cc" class="btn btn-primary btn-lg"><i class="fas fa-calculator mr-2"></i>Click Me</button>
</div>
</div>
<div class="form-row">
<div class="form-group ml-2 col-sm-6">
<label>Menu Item Image</label>
<div id="msg"></div>
<div class="progress" id="uploader">
<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100" style="width: 10%"></div>
</div>
<input type="file" name="img[]" class="file" accept="image/*" id="fileButton">
<div class="input-group my-3">
<input type="text" class="form-control" disabled placeholder="Upload File" id="file" required>
<div class="input-group-append">
<button type="button" class="browse btn btn-primary"><i class="fas fa-folder-open mr-2"></i>Browse...</button>
</div>
</div>
<div class="ml-2 col-sm-6">
<img src=" " id="preview" class="img-thumbnail">
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-block mb-3">Submit Menu</button>
<!-- -------------------------------------------------------------------------- -->
</div>
</form>
And my create menu which clear all fields after form submit.
// create menu
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
fileButton.addEventListener('change', function(e) {
var file = e.target.files[0];
var storageRef = firebase.storage().ref('foodImg/' + file.name);
var task = storageRef.put(file);
task.on('state_changed', function progress(snapshot) {
var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
uploader.value = percentage;
}, function(error) {
console.error(error);
}, function() {
task.snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log('File available at', downloadURL);
const createMenuForm = document.querySelector('#mydropzone');
createMenuForm.addEventListener('submit', (e) => {
e.preventDefault();
db.collection('restaurants').add({
foodLine: {
menuTitle: createMenuForm.menuTitle.value
},
food: {
foodName: createMenuForm.foodName.value,
imageURL: downloadURL,
inputCalories: createMenuForm.inputCalories.value,
menuItemDescription: createMenuForm.menuItemDescription.value,
menuItemInfo: createMenuForm.menuItemInfo.value
}
}).then(() => {
//reset form
createMenuForm.reset();
fileButton.value = "";
var preview = document.getElementById('preview');
preview.value = "";
}).catch(err => {
console.log(err.message);
});
});
});
});
});
Can you try these things also
document.getElementById("myForm").reset();
$("#myForm").trigger("reset");
I think you try to access createMenuForm outside the scope where const createMenuForm was declared.
Try to declare it above the event listener:
// create menu
const createMenuForm = document.querySelector('#mydropzone');
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
// ...
or directly with
document.querySelector('#mydropzone').reset();
i debug and find that preview need to be clean
document.getElementById("preview").src = "#";

Categories

Resources