I have managed to load the image on my page using HTML and JS but I can't seem to post the image to my MongoDB and it won't show on my 'home' page.
HTML:
<div class="container">
<h1 style="text-align: center">Post a New Guitar</h1>
<div class="col-md-6">
<form action="/guitars" method="POST">
<div class="input-group">
<label>Item Name</label>
<div class="input-group">
<input class="form-control" type="text" name="name" placeholder="Name">
</div>
<label>Upload Image</label>
<div class="input-group">
<span class="input-group-btn">
<span class="btn btn-default btn-file">
Browse… <input type="file" id="imgInp">
</span>
</span>
<input type="text" class="form-control" readonly>
</div>
<img id="img-upload"/>
<div class="input-group">
<button class="btn btn-lg btn-primary btn-block">Submit!</button>
</div>
Go Back
</div>
JS:
$(document).ready( function() {
$(document).on('change', '.btn-file :file', function() {
var input = $(this),
label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
input.trigger('fileselect', [label]);
});
$('.btn-file :file').on('fileselect', function(event, label) {
var input = $(this).parents('.input-group').find(':text'),
log = label;
if( input.length ) {
input.val(log);
} else {
if( log ) alert(log);
}
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#img-upload').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
});
When submitting the form, I want it to display the image that has been uploaded using JS and for it to be 'saved' to my database.
What do you mean by "post the image to MongoDB"? You shouldn't be saving image in the database.
What you want to do is when you upload in image, store it in a publicly accessible location in your server. What you save in the database is not the image itself but the location of the image on the server.
Image stored in the server:
/home/public/image.jpg
Image path stored in Mongo DB:
{
path: '/home/public/image.jpg'
}
When you go back to your html page, you just need to query the path of the image in Mongo DB and use that value as a source in your image tag.
`<img src="${path}" />`
Related
Warning: Undefined array key "image"
Showing this error when I'm uploading files in folder and database, I guess my code has mistake.
HTML CODE
<form action="image.php" method="post">
<div class="row">
<div class="col">
<div class="avatar-upload">
<div class="avatar-edit">
<input type='file' id="imageUpload" name="image[]" accept=".png, .jpg, .jpeg" />
<label for="imageUpload"></label>
</div>
<div class="avatar-preview">
<div id="imagePreview" name="image[]"style="background-image: url('../../images/<?
=getuserimagesinfo($db,$user['id'])?>');">
</div>
</div>
</div>
</div>
</form>
Javascript
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#imagePreview').css('background-image', 'url('+e.target.result +')');
$('#imagePreview').hide();
$('#imagePreview').fadeIn(650);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imageUpload").change(function() {
readURL(this);
});
PHP Code
$image_name=$_FILES['image']['name']; //Storing image name
$img_tmp=$_FILES['image']['tmp_name'];
print_r($image_name);
print_r($img_tmp);
If I am inserting name="image[]" in wrong input then please suggest me one, Thanks in advance
I am using Laravel-5.8 for my project. I want to upload image, and click on submit button to save the image and other text fields into the database.
Controller
public function create()
{
$countries = ConfigCountries::all();
return view('organization.companies.create')->with('countries', $countries);
}
public function store(Request $request)
{
try {
$orgStartDate = Carbon::parse($request->org_start_date);
$arr = [
'organisation_code' => $request->organisation_code,
'organisation_name' => $request->organisation_name,
'website' => $request->website,
'org_decription' => $request->org_description,
'total_employees' => $request->total_employees,
'registration_number' => $request->registration_number,
'org_start_date' => $request->$orgStartDate,
'phone_number' => $request->phone_number,
'secondary_phone' => $request->secondary_phone,
'email' => $request->email,
'secondary_email' => $request->secondary_email,
'address1' => $request->address1,
'address2' => $request->address2,
'country_id' => $request->country_id,
'created_by' => Auth::user()->id,
'created_at' => date("Y-m-d H:i:s"),
'is_active' => 1,
];
if ($request->org_image != "") {
$org_image = time() . '_' . $request->org_image->getClientOriginalName();
$request->org_image->move('storage_files/companies/profile/', $org_image);
$arr['org_image'] = 'storage_files/companies/profile/' . $org_image;
}
$company = OrgCompany::create($arr);
$company->save();
Session::flash('success', 'Company is created successfully');
return redirect()->route('organization.companies.index');
} catch (Exception $exception) {
return back()->withInput()
->withErrors(['unexpected_error' => 'Unexpected error occurred while trying to process your request.']);
}
}
view
<div class="card-body">
<form action="{{ route("organization.companies.store") }}" method="post class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<div class="text-center">
<input type="image" class="profile-user-img img-fluid img-circle"
src="{{asset('theme/adminlte3/dist/img/company_logo.png')}}"
id="wizardPicturePreview" title="" width="150">
<input type="file" name="picture" id="wizard-picture" class="" hidden>
<h4 class="profile-username text-center">Click On Image to Add Logo</h4>
</div>
<span style="color:blue;"><h4 class="box-title"><b>Contact Information</b></h4></span>
<hr class="m-t-0 m-b-40">
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label class="control-label text-right col-md-3"> Phone No.</label>
<div class="col-md-9 controls">
<input type="text" name="phone_number" placeholder="Enter Company Phone no. here" class="form-control" value="{{old('phone_number')}}">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group row">
<label class="control-label text-right col-md-3"> Alternative Phone No.</label>
<div class="col-md-9 controls">
<input type="text" name="secondary_phone" placeholder="Enter Alternative Phone no. here" class="form-control" value="{{old('secondary_phone')}}">
</div>
</div>
</div>
<!--/span-->
</div>
<hr>
<div class="form-actions">
<div class="row">
<div class="col-md-6">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn btn-primary">Add Company</button>
<button type="button" onclick="window.location.href='{{route('organization.companies.index')}}'" class="btn btn-default">Cancel</button>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<script>
$(document).ready(function(){
$("#wizard-picture").change(function(){
readURL(this);
});
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#wizardPicturePreview').attr('src', e.target.result).fadeIn('slow');
}
reader.readAsDataURL(input.files[0]);
} }
$("input[type='image']").click(function() {
$("input[id='wizard-picture']").click();
});
$(".form-control").keypress(function(e) {
if (e.which == 13) {
e.preventDefault();
return false;
}
});
</script>
The issue is that without clicking on the save submit button, when I clicked on image file uploader, it redirects to the index page without uploading the image to the screen.
How do I resolve this?
Thanks
An input type of image is a way to define an image as a submit button, so clicking on the image actually is submitting the form. You can either change the image to a regular <img> tag or change you click handler to prevent the default action like so
$("input[type='image']").click(function(e) {
e.preventDefault();
$("input[id='wizard-picture']").click();
});
Also just a heads up, you have a typo in the line that opens your form. There's no closing quotes after method="POST which is probably why the page is just redirecting on submit
Maybe because the closing quote of method is missing in <form> starting tag
I want to send/add notification data in database that contains image with some text data so I am not able to add this data in firebase. I tried some code for only data insertion, but it doesn't work and How do I add image in firebase?
I am adding database which is made manually for notification. I want to add further more notifications with image
database
This is my html form
<form method=post enctype="multipart/form-data">
<div class="row">
<div class="col-md-5">
<div class="form-group">
<label>Title</label>
<input type="text" id="title" class="form-control" placeholder="Company" >
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Image</label>
<input type="image" class="form-control" placeholder="Image">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="exampleInputEmail1">Redeem Steps</label>
<input type="text" id="redeem" class="form-control" placeholder="Redeem Steps">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Description</label>
<textarea rows="5" id="description" class="form-control" placeholder="Here can be your description"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12" >
Image 1 <span style="color:red">*</span><!--<input type="file" id="image" name="img1" required>-->
</div>
</div>
<button type="submit" id="submitBtn" class="btn btn-info btn-fill pull-right" onclick="submitclick()">Send notification</button>
<div class="clearfix"></div>
</form>
this is js file
var title=document.getElementById("title");
var redeem=document.getElementById("redeem");
var description=document.getElementById("description");
var image=document.getElementById("image");
var submitBtn=document.getElementById("submitBtn");
var Id=1;
function submitclick(){
var firebaseref=firebase.database().ref();
var messagetitle=title.value;
var messageredeem=redeem.value;
var messagedescription=description.value;
//var messageimage=image.value;
console.log(messagetitle);
console.log(messageredeem);
console.log(messagedescription);
//console.log(messageimage);
//firebaseref.child("notification").set("vinit");
//firebaseref.child("notification").set("2");
//firebaseref.child("notification").set("messagedescription");
//firebaseref.child("notification").set("messageimage");
firebase.database().ref('notification/'+Id).set({
title : messagetitle,
redeem : messageredeem,
description : messagedescription
image : messageimage
});
console.log(Id);
Id++;
console.log(Id);
}
You cannot upload image directly into the firebase database. You have to upload the image into the firebase storage first, then you can store the image name/location/downloadUrl in the database if you want. Altough, store the download url is not the best practice.
const file = ...
const metadata = { contentType: 'image/jpeg' }; // or whatever you want
const storageRef = firebase.storage().ref();
const uploadTask = storageRef.child(`images/${file.name}`).put(file, metadata);
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, snapshot => {
// If you want to show upload progress, do whatever you want with progress...
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED:
console.log('Upload is paused');
break;
case firebase.storage.TaskState.RUNNING:
console.log('Upload is running');
break;
}
}, error => {
console.log(error);
}, () => {
// upload finished with success, you can get the download URL
uploadTask.snapshot.ref.getDownloadURL().then(downloadURL => {
console.log(downloadURL);
});
});
If you want to store the downloadUrl into the databse then you have to store tha downloadUrl into a variable or put the database set into the upload finished callback.
The database set part should work with this way:
// The id should foloow your database structure,
// based on your posted image, should look like this:
// `noti_${id}` where the id is a number.
firebase.database().ref(`notification/${id}`).set({
...uploadData,
image: downloadUrl
});
Also, I hardly recommend you to use async await to handle promises and use cloud firestore instead of realtime database.
How can I put a delete icon to remove a base64 image record from database record? I've attached CSHTML section of image uploader and the Javascript for the uploader. I've also attached screenshot of the database record. Btw, I'm using C# MVC. Thank you in advance for the help.
The page
Database record
function Picture_Upload(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#Form_Account #PICTURE').val(e.target.result);
};
reader.readAsDataURL(input.files[0]);
$("#lable_file").html($(input).val().split("\\").splice(-1, 1)[0] || '#Language_List.Where(x => x.KEYWORD == "No_File_Chosen").First().VALUE');
}
}
<div class="col-lg-4 well well-sm">
Account Picture
<br /> #if (!String.IsNullOrEmpty(Model.PICTURE)) {
<img src='#Model.PICTURE' style="max-width:100%;max-height:100%" /> } else {
<img src="~/img/Logo_Blank.png" style="max-width:100%;max-height:100%;" /> }
<br /><br />
<div class="Toggle_Form_Account" style="display:none; width:100%">
#*<input id="file_upload" type="file" accept="image/gif, image/jpeg, image/png" onchange="Picture_Upload(this);" />*#
<button type="button" onclick="document.getElementById('file_upload').click()">#Language_List.Where(x => x.KEYWORD == "Choose_File").First().VALUE</button> <label for="file_upload" id="lable_file" style="font-weight: normal !important;">#Language_List.Where(x => x.KEYWORD == "No_File_Chosen").First().VALUE</label>
<input id="file_upload" type="file" style="display:none" accept="image/gif, image/jpeg, image/png" onchange="Picture_Upload(this);" />
</div>
I have an already existing picture and I want to upload a new one and replace the old picture, but this code is not working. (I have a button whose onclick attribute is photoSave().) Can someone tell what's wrong with this Javascript code and maybe write a possible solution?
This is the important part of the code:
<div class="row">
<div class="col-md-12">
<div class="profilePic" id="profilePic">
<img src="prof.jpg" id="pictureToShow" />
</div>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12">
<div id="photoButton">
<label class="btn btn-default btn-file" style="width:220px" onclick="photoChange()">
Profilkép megváltoztatása <input type="file" accept="image/*" style="display: none" id="newPhoto">
</label>
</div>
</div>
</div>
<script type="text/javascript">
function photoChange() {
document.getElementById("photoButton").innerHTML = '<button type="button" style="width:110px" class="btn btn-success btn-s" onclick="photoSave()">Mentés</button><button type="button" style="width:110px" class="btn btn-danger btn-s" onclick="photoSave()">Mégse</button>'
}
function photoSave() {
document.getElementById("photoButton").innerHTML = '<label class="btn btn-default btn-file" style="width:220px" onclick="photoChange()">Profilkép megváltoztatása<input type="file" accept="image/*" style="display: none"></label>'
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#pictureToShow').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
When you're uploading a file via input type="file", the file is not yet saved in your server.
Two solutions:
So you need to put this file in your resources repo on your web
server.
Or you can preview the image, see
Preview an image before it is uploaded
Add the following js in your function:
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#pictureToShow').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
Moreover, your image does not have an ID attribute, so you need to change <img src="prof.jpg" /> for <img src="prof.jpg" id="pictureToShow" />.