Multiple image files and using file reader to preview - javascript

I have to upload multiple image file and I need to show the the preview of the image.
But the problem I'm facing using following javascript is image got changed when i upload the other image, means when i upload the feature_image, the product_image which i uploaded earlier being replaced by the new one and there is code redundancy there as i used same function for different different id, how do I solve the issue with optimized solution..Thanks in Advance
HERE is the HTML part:
<div class="form-group">
<label>Product Image</label>
<input type="file" name="product_image" id="product_image" width="200px">
<img src="" id="product-img-tag" width="200px" />
</div>
<div class="form-group">
<label>Feature Image</label>
<input type="file" name="feature_image" id="feature_image" width="200px">
<img src="" id="feature-img-tag" width="200px" />
</div>
<div class="form-group">
<label>Slurp Image</label>
<input type="file" name="slurp_image" id="slurp_image" width="200px">
<img src="" id="slurp-img-tag" width="200px" />
</div>
Here is the javascript part :
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#product-img-tag').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#product_image").change(function(){
readURL(this);
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#feature-img-tag').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#feature_image").change(function(){
readURL(this);
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#slurp-img-tag').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#slurp_image").change(function(){
readURL(this);
});

Optimized solution : don't use a FileReader, use the URL.createObjectURL(blob) method.
When the blobs passed to this method come from an <input type="file">, the URI returned is a direct pointer to the file on the user system, hence it is faster, less memory consumptive and easier to use (since synchronous) than a FileReader and its toDataURL method.
Short version with your markup
// attach our event listener on all the inputs
document.querySelectorAll('input[type="file"]').forEach(function(input){
input.addEventListener('change', readURL);
});
function readURL(evt) {
// here we can use 'this', it will be the input
var img = this.nextElementSibling;
// not really needed in this case but it's a good habit to revoke the blobURI when done
img.onload = function(){URL.revokeObjectURL(this.src)};
img.src = URL.createObjectURL(this.files[0]);
}
<div class="form-group">
<label>Product Image</label>
<input type="file" name="product_image" id="product_image" width="200px">
<img src="" id="product-img-tag" width="200px" />
</div>
<div class="form-group">
<label>Feature Image</label>
<input type="file" name="feature_image" id="feature_image" width="200px">
<img src="" id="feature-img-tag" width="200px" />
</div>
<div class="form-group">
<label>Slurp Image</label>
<input type="file" name="slurp_image" id="slurp_image" width="200px">
<img src="" id="slurp-img-tag" width="200px" />
</div>
Longer version based on ids
document.querySelectorAll('input[type="file"]').forEach(function(input){
input.addEventListener('change', readURL);
});
function readURL(evt) {
var img_id;
switch(this.id){
case "product_image" : img_id = "product-img-tag"; break;
case "feature_image" : img_id = "feature-img-tag"; break;
case "slurp_image" : img_id = "slurp-img-tag"; break;
}
var img = document.getElementById(img_id);
if(!img){
return;
}
img.onload = function(){URL.revokeObjectURL(this.src)};
img.src = URL.createObjectURL(this.files[0]);
}
<div class="form-group">
<label>Product Image</label>
<input type="file" name="product_image" id="product_image" width="200px">
<img src="" id="product-img-tag" width="200px" />
</div>
<div class="form-group">
<label>Feature Image</label>
<input type="file" name="feature_image" id="feature_image" width="200px">
<img src="" id="feature-img-tag" width="200px" />
</div>
<div class="form-group">
<label>Slurp Image</label>
<input type="file" name="slurp_image" id="slurp_image" width="200px">
<img src="" id="slurp-img-tag" width="200px" />
</div>

Related

Error during uploading file in folder and database

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

Picture delete/remove code syntax using cshtml (base64 image)

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>

Javascript - Image preview before upload. Needed on multiple instances on same page

I have a page that has multiple fields to upload images individually and I wanted a script that would allow the user to preview the image before submitting.
I used this script on the first field and it works fine.
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#main').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
However, it doesn't work for the remainder of the previews even if I make them unique. What should I do in order to copy the same script and have it work on multiple instances on the same page?
Update:
The html for the preview looks like this:
<div class="row">
<div class="col-md-3">
<h5>Main Photo:</h5>
<input class="form-control" type="file" name="main" onchange="readURL(this);" />
</div>
<div class="col-md-3">
<h6>Preview:</h6>
<img id='main' style="height:100px;" />
</div>
<div class="col-md-3">
<h5>Front Photo:</h5>
<input class="form-control" type="file" name="front" onchange="readURL(this);" />
</div>
<div class="col-md-3">
<h6>Preview:</h6>
<img id='front' style="height:100px;" />
</div>
</div>
Perhaps you could make use of the unique name attribute of the <input /> fields to access the specific/corresponding image element for previewing the file like so:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
// Use the input element's name attrbute to select and
// update the image element with matching id
$('#' + input.name).attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="row">
<div class="col-md-3">
<h5>Main Photo:</h5>
<input class="form-control" type="file" name="main" onchange="readURL(this);" />
</div>
<div class="col-md-3">
<h6>Preview:</h6>
<img id='main' style="height:100px;" />
</div>
<div class="col-md-3">
<h5>Front Photo:</h5>
<input class="form-control" type="file" name="front" onchange="readURL(this);" />
</div>
<div class="col-md-3">
<h6>Preview:</h6>
<img id='front' style="height:100px;" />
</div>
</div>
Preview a file (image) before it is uploaded, on multiple instances on the same page.
Just use image input field name to id for img to show. Check the simple and clean code below with demo to jsfiddle.
$("input[type=file]").change(function() {
readURL(this);
filename = this.files[0].name;
console.log(filename);
});
// image file upload preview
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#' + input.name).attr('src', reader.result);
}
reader.readAsDataURL(input.files[0]);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<label>User Image</label>
<input type="file" name="user_image"> <br />
<img id="user_image" style="width:75px;" />
<hr />
<label>User Signature</label>
<input type="file" name="user_signature"> <br />
<img id="user_signature" style="width:75px;" />
</form>

get and load image from input type url using javascript

I have input type "URL" in my HTML file.
How to write JavaScript to fetch image from user entered URL and load it using javascript
<div class="url-container">
<input type="url" class="form-control" placeholder="Insert image URL" id="image-url">
<button class="btn btn-default" type="submit" id="url_submit">
<i class="material-icons">cloud_download</i>
</button>
</div>
i want to load it here:
<img class="materialboxed" src="" id="image" style="">
You can just change the src attribute of the image:
document.getElementById("b").addEventListener("click", e => {
let imageInput = document.getElementById("image-input");
let image = document.getElementById("image");
if (imageInput.value) image.src = imageInput.value;
});
<input type="url" id="image-input">
<button id="b">Change Image</button>
<br>
<img src="" id="image">
Or, with jQuery:
$("#b").click(e => {
let imageInput = $("#image-input");
let image = $("#image");
if (imageInput.val()) image.attr("src", imageInput.val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="url" id="image-input">
<button id="b">Change Image</button>
<br>
<img src="" id="image">
$('#url_submit').click(function(e) {
e.preventDefault();
$('.materialboxed').attr('src', $('#image-url').val());
}

Saving and displaying uploaded image

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" />.

Categories