How to Upload image with some field? - javascript

I am trying to upload image with some required field like name, description. When i am inserting data without the image field it works, but when trying to upload the image file as well its not inserting data to database. Could anyone tell me what may be wrong with my code?
Controller
public function store(Request $request)
{
$this->validate($request, [
'cat_name' => 'required|max:255',
'description' => 'required|min:6',
'cat_pic' => 'required|image|mimes:jpg,jpeg,png',
]);
$fileName = null;
if ($request()->hasFile('cat_pic')) {
$file = $request()->file('cat_pic');
$fileName = time().'.'.$file->getClientOriginalExtension();
$destinationPath = public_path('/uploads/products/cats/');
$file->move($destinationPath, $fileName);
$this->save();
}
Catagories::create([
'cat_name' => $request->input('cat_name'),
'description' => $request->input('description'),
'cat_pic' => $fileName,
]);
Session::flash('alert', __('messages.created'));
Session::flash('alertClass', 'success');
return redirect()->route('catagories');
}
View
<div class="col-md-4 offset-5">
<div class="form-group">
<form role="form" action="<?php echo e('/products/cats') ?>" method="POST" id="createcat" >
{{ csrf_field() }}
<p>
Create New Product Category
</p>
<div class="form-group">
<label for="cat_name">
Name*:</label>
<input type="text" class="form-control"
id="cat_name" name="cat_name" required maxlength="50">
</div>
<div class="form-group">
<label for="cat_pic">Category Image* </label>
<input data-preview="#preview" class="form-control" name="cat_pic" type="file" id="cat_pic">
<img class="col-md-6" id="preview" height="100px" width="20px" src="">
</div>
<div class="form-group">
<label for="description">
Description*:</label>
<textarea class="form-control" type="textarea" name="description"
id="description" placeholder="Category Description"
maxlength="600" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-lg btn-success btn-block" id="btncreatecat">Create</button>
</form>
</div>
</div>
#endsection
#push('scripts')
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#cat_pic").change(function(){
readURL(this);
});
</script>
Route
Route::resource('products/cats', 'Admin\CatController');
and some JQuery to preview the image
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#cat_pic").change(function(){
readURL(this);
});
</script>

you need to add enctype="multipart/form-data" to the <form> tag.
Like this:
<form role="#" action="#" method="#" id="#" enctype="multipart/form-data">
So your form can send other things than text.

I realized the problem is I just forgot to add enctype="multipart/form-data" inside the form tag.

Related

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?

JQuery File Input - Read image width & height

I'm trying to read (input type="file") image file's original width / height. My code gives me "undefined". I suppose because i'm not loading image to server or anywhere.
Here is my code;
<script>
$( document ).ready(function() {
$('#texture_modal').click(function () {
var texture_name = $('#texture_name').val();
var thumb_img = $('#thumb_img').val().replace(/^.*\\/, "");
var big_img = $('#big_img').val().replace(/^.*\\/, "");
var real_img = $('#real_img').val().replace(/^.*\\/, "");
var img_size = document.getElementById("real_img").files[0].size / (1024*1024); // Get real_img size in MB
var texture_size = img_size.toFixed(2); // get rid of decimals in real_img size MB
var texture_category = $('#texture_category').val();
var texture_description = $('#texture_description').val();
// THIS IS THE STUFF WHICH I WANT TO GET IMAGE WIDTH
var texture_dim = document.getElementById("real_img").naturalWidth;
console.log(texture_dim);
}); //End click function
}); //End document ready
</script>
And here is my input fields. I have multiple file inputs, whichs are for thumbnail image, big image and real image. I need real image width only, others will be upload to server. Here is my input fields;
<!-- this fields are inside a bootstrap modal -->
<div class="modal-body">
<div class="input-group input-group-sm">
<div class="input-group-prepend">
<span class="input-group-text"><small>Texture Name</small></span>
</div>
<input type="text" class="form-control" id="texture_name">
</div>
<div class="form-group pt-1">
<small>Thumbnail Img(200*200)</small>
<input type="file" class="form-control form-control-sm" id="thumb_img">
<small>Big Img(445*445)</small>
<input type="file" class="form-control form-control-sm" id="big_img">
<!-- this one i want to take width without post or upload anywhere -->
<small>Real Img</small>
<input type="file" class="form-control form-control-sm" id="real_img">
<!-- taking categories with php function -->
<small>Category</small>
<select id="texture_category" class="form-control form-control-sm">
<option selected disabled>----- Choose a Category -----</option>
<?php foreach($texture_categories as $key){?>
<option><?php echo $key; ?></option>
<?php } ?>
</select>
<small>Description :</small>
<textarea id="texture_description" class="form-control form-control-sm"></textarea>
</div>
</div>
can you try to assign an Image and get it
var fileUpload=document.getElementById("photoInput");
function Test(){
var reader = new FileReader();
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function (e) {
var image = new Image();
image.src = e.target.result;
image.onload = function () {
var width = this.naturalWidth || this.width;
var height = this.naturalHeight || this.height;
console.log(height,width)
}
};
}
<div class="photo">
<input type="file" name="photo" id="photoInput" onchange="Test(this)"/>
</div>
in your example
$( document ).ready(function() {
$(".modal").modal()
});
function Test(){
var fileUpload=document.getElementById("thumb_img");
var reader = new FileReader();
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function (e) {
var image = new Image();
image.src = e.target.result;
image.onload = function () {
var width = this.naturalWidth || this.width;
var height = this.naturalHeight || this.height;
console.log(height,width)
}
};
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<!-- this fields are inside a bootstrap modal -->
<div class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<div class="input-group input-group-sm">
<div class="input-group-prepend">
<span class="input-group-text"><small>Texture Name</small></span>
</div>
<input type="text" class="form-control" id="texture_name">
</div>
<div class="form-group pt-1">
<small>Thumbnail Img(200*200)</small>
<input type="file" class="form-control form-control-sm"onchange="Test(this)" id="thumb_img">
<small>Big Img(445*445)</small>
<input type="file" class="form-control form-control-sm" id="big_img">
<!-- this one i want to take width without post or upload anywhere -->
<small>Real Img</small>
<input type="file" class="form-control form-control-sm" id="real_img">
<!-- taking categories with php function -->
<small>Category</small>
<select id="texture_category" class="form-control form-control-sm">
<option selected disabled>----- Choose a Category -----</option>
<?php foreach($texture_categories as $key){?>
<option><?php echo $key; ?></option>
<?php } ?>
</select>
<small>Description :</small>
<textarea id="texture_description" class="form-control form-control-sm"></textarea>
</div>
</div>
</div>
</div>
</div>

Insert readAsDataURL in [img]base64[/img] tag

My code, i have Jquery:
<div class="form-row">
<input class="form-group col-md-6" id="fileinput" type="file" accept="image/gif, image/jpeg, image/png" onchange="readURL(this);" />
</div>
<div class="form-group">
<label for="content">Message</label>
<textarea id="content" name="content" rows="10" class="form-control" placeholder="Écrivez un message ..."></textarea>
</div>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$("#fileinput").attr("src", e.target.result);
$("#content").val(e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
I want to add the base64 img in a bbcode editor (textarea is #content).
Actually is work, but i want to have this:
[img]data:image/png;base64,iVBORw0KGgoAAAAN...[/img]
Thank you.
Assuming you've successfully included jQuery as your script suggests, and your HTML looks a bit like this (simplified):
<html>
<body>
<input type="file" id="file"/>
<img id="content"/>
</body>
</html>
Then a script like this will do what you want:
$(function() {
function readURL() {
// Grabbing the DOM object, so that the code follows your general pattern
input = $(this)[0];
if (input.files && input.files.length) {
var reader = new FileReader();
reader.onload = function () {
// The attribute you want to change on an img tag is "src" not "val"
$("#content").attr("src", reader.result);
}
reader.readAsDataURL(input.files[0]);
}
}
// Bind the readURL function to the change event on our file input
$("#file").change(readURL);
});

HTML required functions with javascript which required function doesnt work

Can anyone help me with this required function doesnt work. i am uploading a picture in my html/php web page and before i upload a picture i set a dropdown option which is to upload or not, and this is my code:
<script>
function papeles()
{
var x = document.getElementById('tagoan1').value;
if (x == "YES")
{
// alert('aaaa');
$('#imgInp').addClass("required");
$('#imgInp').removeClass("hidden");
$('#blah').removeClass("hidden");
} else
{
//alert('bbbbb');
$('#imgInp').addClass("hidden");
$('#imgInp').removeClass("required");
$('#blah').addClass("hidden");
}
}
</script>
<div class="col col-sm-5">
<label>Attachment </label>
<select class="form-control" id="tagoan1" name="taguan" onchange="papeles()" required disabled>
<option value="">With Attachment?</option>
<option value="YES">Yes</option>
<option value="NO">No</option>
</select>
</div>
<div class="row text-center">
<div class="col col-sm-6">
<div class="form-group" style="margin:0;">
<input type='file' name="image" id="imgInp" value="" class="hidden required btn btn-block btn-sm" style="padding-left:3em;width:300px"/>
</div>
<img id="blah" src="customer/tagoan/images/noimage.png" height="200px" width="300px" name="tae" border-color="white" placeholder="" class="hidden"/>
</div>
</div>
<script src="js/jquery-1.11.3.min.js"></script>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function () {
readURL(this);
});
</script>
The problem is that when i click yes but i dont choose a file, the picture will still submit it should not submit because of the add class required how to solve this.
when you hide an input, it is not removed from the page. So, the file input stays in the form, and sumbitted regardless if it's hidden or not. What you need is to remove the input from DOM:
if (x == "YES")
{
$('#imgInp').remove() // file input gone
$('#blah').removeClass("hidden");
} else
{
//you should add an ID to the parent of imgInp instead of referring as .form-group
$('.form-group').prepend("<input type='file' name='image' id='imgInp' value='' class='required btn btn-block btn-sm' style='padding-left:3em;width:300px'/>")
$('#blah').addClass("hidden");
}
is it okay if you just use .hide() and .show() of jQuery?

Image not send using javascript when submit form no refresh page

I have a javascript using send text and photo, my problem is photo not send in my directory folder and empty column photo in database.
How to fix this? I'm confused :(
This is my screenshot result
index.php
<script>
$(function () {
$('#fr_testi').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'testi.php',
data: $('#fr_testi').serialize(),
success: function () {
document.getElementById("sc_testi").innerHTML = "Succes :)";
$('#nama_testi').val("");
$('#status_testi').val("");
$('#foto_testi').val("");
$('#komentar_testi').val("");
}
});
});
});
</script>
<form method="POST" id="fr_testi" enctype="multipart/form-data">
<div class="control-group">
<label class="control-label">Nama</label>
<div class="controls">
<input name="nama" id="nama_testi" maxlength="100" type="text" required>
<input type="hidden" value="<?php echo $sk->kode?>" name="kode">
</div>
</div>
<div class="control-group">
<label class="control-label">Status</label>
<div class="controls">
<input id="status_testi" name="status" maxlength="100" type="text" required>
</div>
</div>
<div class="control-group">
<label class="control-label">Foto</label>
<div class="controls">
<input name="foto" id="foto_testi" type="file" required>
</div>
</div>
<div class="control-group type2">
<label class="control-label">Komentar</label>
<div class="controls">
<textarea maxlength="250" id="komentar_testi" name="komentar" required></textarea>
</div>
</div>
<center>
<button type="submit" class="button button_type_2 button_grey_light">Send</button><br/><br/>
<font color="green" id="sc_testi"></font>
</center>
</form>
testi.php
<?php
include "element/koneksi.php";
$nama = $_POST['nama'];
$kode = $_POST['kode'];
if ($nama!=NULL or $kode!=NULL) {
date_default_timezone_set("Asia/Jakarta");
$tglnya = date("Y-m-d");
$status = $_POST['status'];
$komentar = $_POST['komentar'];
$warna = "#52B3D9";
$kon = "NO";
$namafile_tmp = $_FILES['foto']['tmp_name'];
if($namafile_tmp){
$namafile = $_FILES['foto']['name'];
$file = $kode."_".$tglnya."_".$namafile;
copy($namafile_tmp, "images/sekolah/testimoni/{$file}");
unlink($namafile_tmp);
}
$query= "INSERT INTO sekolah_testimoni VALUES(id_testi,'$kode','$nama','$komentar','$status','$file','$warna',now(),'$kon','$kon')";
mysql_query($query);
}
else
{
echo "<script language='JavaScript'>window.history.back() </script>";
}
?>
The jquery method serialize doesn't include input file type.
If you just want to register filename on DB, you can use JS like below instead of serialize.
sendData = "";
$.each($("#formulario input, #formulario select"), function () {
if ($(this).prop("type") == "submit") return;
sendData += sendData!=""?"&":"";
sendData += $(this).prop("name") + "=" + $(this).val()
});
But if you want to upload file, save on the server and then register the location on DB, you should post directly from HTML or use FormData javascript object to perform this task.
fileInputElement = document.getElementById("yourFileInputID");
var formData = new FormData();
formData.append("userfile", fileInputElement.files[0]);
// if you need to upload multiple files you should loop through the fileInputElement.files array, appending one by one
var request = new XMLHttpRequest();
request.open("POST", "http://yourURL/");
request.send(formData);
Unfortunately this method doesn't work on old browsers. To get upload working on those you should use an iframe solution (post form to an invisible iframe without leaving the page).

Categories

Resources