jquery preview image not working - javascript

So I'm trying to implement a preview button so that when my users clicks on the upload button image they could have a preview but the thing is that it is not working, I wonder why ?? A brief description : I have a js function that creates new elements and append it to a p tag date. It is in this function that is going to create the preview image code
// code for creating new elements
function createElements(){
const userQuestions = document.querySelector('#userQuestions');
userQuestions.insertAdjacentHTML(
'beforeend', '<div class="uploader" onclick="$(\'#filePhoto\').click()"><p id="bg-text">No image</p></div><input type="file" name="userprofile_picture" id="filePhoto" style="display:block;width:185px;" /></center><div class="grid-container">'
);
}
///Code to preview image
function handleImage(e) {
var imageLoader = document.getElementById('filePhoto');
imageLoader.addEventListener('change', handleImage, false);
var reader = new FileReader();
reader.onload = function (event) {
$('.uploader').html( '<img width="300px" height="350px" src="'+event.target.result+'"/>' );
}
reader.readAsDataURL(e.target.files[0]);
}
.uploader {width:50%;height:35%;background:#f3f3f3;border:2px dashed #0091ea;}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="userQuestions"></div>
<button type="button" onclick="createElements()">add elements</button>
</body>
</html>
If you run the snippet above you can see that the button is woeking but the preview is not showing. Could someone help me?

HTML:
<div class="row">
<div class="col-xs-4">
<div class="form-group">
<label>Company Logo</label>
<input type="file" class="form-control" value="" name="companyLogo" id="companyLogo" accept="image/*" />
</div>
</div>
<div id="displayImage">
<img id="imgData" src="#" alt="your image" height="150px" width="150px" />
</div>
</div>
JavaScript:
$("#companyLogo").change(function(e) {
if(e.target.value === "") {
$("#displayImage").hide();
} else {
$("#displayImage").show();
}
readURL(this);
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$("#imgData").attr("src", e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}

Short n simple
No need to create an element on click.
Just add an image tag and set a default image like no image selected or something like that.
The following code will help you
<input type="file" name="myCutomfile" id="myCutomfile"/>
<img id="customTargetImg" src="default.jpg" width="400" height="250">
$("#myCutomfile").change(function() {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#customTargetImg').attr('src', e.target.result);
}
reader.readAsDataURL(this.files[0]);
}
});

Take advantage of jQuery -- particularly using
event handlers
delegated event handlers for dynamically-created elements
tree traversal methods.
$(function() {
var userQuestions = $('#userQuestions');
// create onclick event handler for your button
$('#addElements').click(function() {
// IDs must be unique - since you can have an arbitrary number of filePhoto, use a class instead
userQuestions.append(
'<div class="uploader"><p id="bg-text">No image</p></div><input type="file" name="userprofile_picture" class="filePhoto" /><div class="grid-container"></div>'
);
});
// create delegated onclick event handler for your .uploader
userQuestions.on('click', '.uploader', function() {
// you only want to target the file input immediately after it
$(this).next('[type=file]').click();
});
// create delegated onchange event handler for your .filePhoto
userQuestions.on('change', '.filePhoto', function() {
// find related uploader
var uploader = $(this).prev('.uploader');
// check file was given
if (this.files && this.files.length) {
var reader = new FileReader();
reader.onload = function(event) {
uploader.html('<img width="300px" height="350px" src="' + event.target.result + '"/>');
}
reader.readAsDataURL(this.files[0]);
}
});
});
.uploader {
width: 50%;
height: 35%;
background: #f3f3f3;
border: 2px dashed #0091ea;
}
.filePhoto {
display: block;
width: 185px;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="userQuestions"></div>
<!-- added ID attribute -->
<button type="button" id="addElements">add elements</button>
</body>
</html>
Edit
This answer is a non-jQuery solution based off your comment.
// code for creating new elements
function createElements() {
// no need to document.querySelector if the selector is an ID
const userQuestions = document.getElementById('userQuestions');
// you want to use onclick/onchange attributes here as they are dynamically created
userQuestions.insertAdjacentHTML(
'beforeend', '<div class="uploader" onclick="selectFile(this)"><p id="bg-text">No image</p></div><input type="file" name="userprofile_picture" onchange="handleImage(this)" />'
);
}
// trigger click on file input that follows the uploader
function selectFile(uploader) {
uploader.nextSibling.click();
}
///Code to preview image
function handleImage(input) {
if (input.files.length) {
var reader = new FileReader();
reader.onload = function(e) {
input.previousSibling.innerHTML =
'<img width="300px" height="350px" src="' + e.target.result + '"/>';
}
reader.readAsDataURL(input.files[0]);
}
}
.uploader {
width: 50%;
height: 35%;
background: #f3f3f3;
border: 2px dashed #0091ea;
}
.filePhoto {
display: block;
width: 185px;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="userQuestions"></div>
<button type="button" onclick="createElements()">add elements</button>
</body>
</html>

Related

iframe pdf preview at change event

$(document).ready(function(){
$("#id_quotationFile").change(function(){
url=$("#id_quotationFile").attr(value);
$("#pdf-view").attr("src",url);
});
});
Trying to load pdf file browsed in input field using above jquery code but not working
<input type=file id="id_quotationFile">
<iframe src="" id="pdf-view" frameborder="0px" title="Preview"></iframe>
How to preview pdf file in iframe.
Consider the following.
$(function() {
function readURL(input, target) {
input = $(input).get(0);
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$(target).attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
$(".details").html("Preview: '" + input.files[0].name + "' Type: " + input.files[0].type);
}
}
$("#fileUpload").click(function() {
$("#id_quotationFile").trigger("click");
});
$("#id_quotationFile").change(function() {
readURL(this, $("#pdf-view"));
});
});
input {
display: none;
}
button {
padding: 0.2em 0.4em;
margin: 0.2em;
}
iframe {
width: 95%;
height: 840px;
}
.details {
font-family: Arial, Monospace;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="fileUpload">Browse...</button>
<input type=file id="id_quotationFile">
<span class="details"> </span>
<iframe src="" id="pdf-view" frameborder="0px" title="Preview"></iframe>
Reference: Preview an image before it is uploaded
You need to convert the local file into a new FileReader. So we read the File, convert it into a Base64, and when it's ready, load it into the Target.
As mentioned in this question, try to force your iframe to reload:
document.getElementById('some_frame_id').contentWindow.location.reload();
What’s the best way to reload / refresh an iframe?
In your case it will be:
$("#pdf-view").contentWindow.location.reload();

Display an image who is in bytes of array in my View

My goal is:
I load a person's data into a template that I send to my view.
The user can modify his data and click on 'Submit'.
Almost everything works as it should except for the image.
Indeed, in the method of my controller, I receive the image in bytes of array and I do not find how to display it in my view.
I found several explanations on the net where it is written that I have to use the URI scheme.
But I do not know how since my controller send this data in my code js.
I'd like to say that the input with #Model.Member_Picture contains exactly "value="System.Byte[]".
Could you enlighten me?
(I just post the code related to the image).
Model
[ContainerDataFor("Picture_gr")] // use the name in your C# model
public byte[] Member_Picture { get; set; }
View
<div class="form-check-inline col-xs-6" style="margin-top:2%">
<img id="ItemPreview" src="" accept="image/png, image/jpeg"/>
</div>
<div class="form-check-inline col-xs-6" style="margin-top:2%">
#Html.LabelFor(model => model.Member_Picture, "Upload Picture", new { htmlAttributes = new { #id = "test" } })
<input type="file" class="form-control-file" name="file" id="file" value="#Model.Member_Picture">
<small id="fileHelp" class="form-text text-muted">Maximum 1024kb</small>
</div>
$(document).ready(function () {
var img = $('#test').val();
$('#ItemPreview').attr('src', `data:image/png;base64,${img}`);
});
You cannot use value attribute inside <input type="file" /> to render the image. You need to render the image as Base64 string with this setting:
#{
var base64Image = Convert.ToBase64String(Model.Member_Picture);
var source = String.Format("data:image/png;base64,{0}", base64Image);
}
<img src="#source" width="100%" height="100%" />
Or create another string property like this:
public byte[] Member_Picture { get; set; }
public string Image
{
get
{
return String.Format("data:image/png;base64,{0}", Convert.ToBase64String(Member_Picture));
}
}
And show it in the view:
<img src="#Model.Image" width="100%" height="100%" />
change your src to src="data:image/png;base64, +data" where the data is the byte array of the image
<img id="ItemPreview" src="data:image/png;base64, #Model.Member_Picture">
example
<div>
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAAEsBAMAAACLU5NGAAAAG1BMVEUAmf////8fpf9fv/8/sv+f2P/f8v9/zP+/5f8U6SNkAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAC1UlEQVR4nO3Xz0/aYBzH8doW8biOH3IsoswjDJd4bBnuTBez7GjN5nbUxOxMXaL+2fs+T4t92g6ywyO7vF8J7Ye0ha/fp34BxwEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMD/5c5mYRE/njVT02j2vkj+bN5IllwEQdC/1fUlQTAIq6nJl2PBDx1PJD3UkiWtwX3ong9UjA/n7q9ONTUlT3NnlK1UgcF9+C6dVJIt7Uht75bSon4omywy01/c66t6shley+a0W0l2HbyRx1uVxldm2ihTj1A27k0l2dWWQuKlTh0zbXQXOn4vTxMjWeZJWUmo48BMG01Dp6V76uytjGRZSxaxWIPMTEo7L9KLzAsSx9m/0knWv0yWDWXZ8pVQy1Mmfexa76Yr43xXTtnTS63Wv0x2uTdyqxzmeTopk9756v/S8SpLOpZSYz3sHK9jJKv85KF80XhSpmKv2lVp1oWateuqO0ay6OtjcCk7rxg7w9syFVVLu4xmtZ7TXqQKjfRT99BINst6Tr9H28pS7TKa1Xp+7F++flnyeue9rWX5/VF1WIyy5Q7KkrdYbivLidNV9Xyvt5Oy2t2XGzae+LVbXg4HYe2Cu2h9WM6OX+OWV2QOvYyFqEzrw9PsunaBDLr1WOgaybbB5nGqZlY+uwzyQfP649Rxfm7+8NEzK661a3+1iw8f1aC8OW4laWpm1dslDSqaMzSTZV5nyxcbPbNq7ZpOdvHFZl/+3gN9xw5XZtIl65lVa1cqz/TXV1cdLZMtJ+rd3GyiPq/lxd00MpNRXpzv3M9qe6o6Of6mNt1KsmU8ODsaJXokfOrNj5NuNQkv3/lhXlb6e370IVAjwU8vjy6CqJKsOZffUj39lu6XZmryMrlAt8w5SZvJGn/x8svzeNFMTYtFWCR3ETUSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD4N38AsX524K81XMUAAAAASUVORK5CYII=" alt="Red dot" />
</div>
You can do it like this with vanilla Javascript:
var fileInput = document.getElementById('img-input');
var demo = document.getElementById('demo');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var imageType = /image.*/;
if (file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function(e) {
demo.src= e.target.result;
}
reader.readAsDataURL(file);
} else {
demo.src = '';
console.log('file not supported');
}
});
#demo {
margin-top: 20px;
}
#img-input {
background-color: #4CAF50;
border: none;
color: white;
text-align: center;
padding: 12px 20px;
display: inline-block;
font-size: 18px;
margin: 20px auto;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input type="file" id="img-input" name="file"></div>
<!-- this is where we display the choosen image //-->
<img id="demo" src="#" alt="your image here" />

How to display multiple thumbnails while uploading images in html using javascript?

function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#documentUpload')
.attr('src', e.target.result)
};
reader.readAsDataURL(input.files[0]);
}
}
<html>
<head></head>
<body>
<ul>
<li>
<input type='file' onchange="readURL(this);" />
<img id="documentUpload" src="#" alt="first image" />
</li>
<li>
<input type='file' onchange="readURL(this);" />
<img id="documentUpload" src="#" alt="second image" />
</li>
</ul>
</body>
</html>
> Blockquote
" In example , click on any choose image button but image will be displayed in first case only . I changed the id in both case and in javascript as well but it didnt work.
code above is solution to how to display image in html "
The problem is ID require be unique. In this example, I add an attribute called document-up, and it works. It's possible in this case select more than one element using attributes or classes.
function readURL(input,option) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
if (option == 1){
$("#documentUpload1")
.attr('src', e.target.result)
} else {
$("#documentUpload2")
.attr('src', e.target.result)
}
};
reader.readAsDataURL(input.files[0]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html>
<head></head>
<body>
<ul>
<li>
<input id="input1" type='file' onchange="readURL(this,1);" />
<img id="documentUpload1" document-up src="#" alt="first image" />
</li>
<li>
<input id="input2" type='file' onchange="readURL(this,2);" />
<img id="documentUpload2" document-up src="#" alt="second image" />
</li>
</ul>
</body>
</html>
Here's an approach that will work for an arbitrary number of images and an arbitrary number of images per file-picker.
All you need to is wrap the #previewHolder div with a form and handle its submission.
function newEl(tag){return document.createElement(tag)}
function byId(id){return document.getElementById(id)}
function allByTag(tag,parent){return (parent == undefined ? document : parent).getElementsByTagName(tag)}
// useful for HtmlCollection, NodeList, String types
function forEach(array, callback, scope){for (var i=0,n=array.length; i<n; i++)callback.call(scope, array[i], i, array);} // passes back stuff we need
// callback gets data via the .target.result field of the param passed to it.
function loadFileObject(fileObj, loadedCallback){var a = new FileReader();a.onload = loadedCallback;a.readAsDataURL( fileObj );}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt)
{
byId('addBtn').addEventListener('click', onAddBtnClicked, false);
}
/* html below function needs to create - we dont bother with the img here, since we create as needed when file/s picked */
/*
<div class='item'>
<img height='100px' width='100px'/><br>
<input type='file'/>
</div>
*/
function onAddBtnClicked(evt)
{
var wrapper = newEl('div');
wrapper.className = 'item';
// var img = newEl('img');
// img.style.height = '100px';
// wrapper.appendChild(img);
var input = newEl('input')
input.type = 'file';
// input.multiple = 'true'; // file-inputs are single-selection only be default.
input.addEventListener('change', onFileChanged, false);
input.name = 'inputFiles[]'; // all inputs to get same name. Name to include [] so php can retrieve all files
wrapper.appendChild(input);
byId('previewHolder').appendChild(wrapper);
}
function onFileChanged(evt)
{
var numFiles = this.files.length;
var itemWrapper = this.parentNode;
var fileInput = this;
if (numFiles == 0)
{
// no files chosen, so remove this preview/file-picker element
var previewHolder = itemWrapper.parentNode;
previewHolder.removeChild(itemWrapper);
}
else
{
// remove all/any existing images
while (allByTag('img', itemWrapper).length != 0)
itemWrapper.removeChild( allByTag('img', itemWrapper)[0] );
forEach(this.files, loadAndPreviewImage);
function loadAndPreviewImage(fileObj)
{
loadFileObject(fileObj, onFileObjLoaded);
function onFileObjLoaded(evt) //.target.result;
{
var img = newEl('img');
img.style.height = '100px';
img.src = evt.target.result;
itemWrapper.insertBefore(img, fileInput);
}
}
}
}
.item
{
border: solid 1px black;
border-radius: 6px;
padding: 4px;
}
.button:hover
{
background-color: #b0ffb0;
cursor: pointer;
}
<div id='previewHolder' style='width: 200px'>
<div class='button' id='addBtn' style='text-align:center;padding: 4px'><svg xmlns="http://www.w3.org/2000/svg" height="32" width="32" viewBox="0 0 32 32">
<g transform="translate(0 -1020)" stroke="#00c03b" fill="none">
<circle cx="16" cy="1036" r="14.5" stroke-width="2.998"/>
<path d="m8 1036h16" stroke-linecap="round" stroke-width="3"/>
<path d="m16 1044v-16" stroke-linecap="round" stroke-width="3"/>
</g>
</svg></div>
</div>

How to put a default image in a img

I want to do is make a default image to the img tag if the user has not choose a profile picture on his account.
current output:http://jsfiddle.net/LvsYc/2973/
http://s38.photobucket.com/user/eloginko/media/profile_male_large_zpseedb2954.jpg.html
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);
});
Here's a fiddle showing what was mentioned in the comments:
HTML
<form id="form1" runat="server">
<input type='file' id="imgInp" />
<div class="img">
<img id="blah" src="#" alt="your image" />
</div>
</form>
CSS
img {
width: 120px;
height: 120px;
}
img[src="#"] {
display: none;
}
.img {
background: url('http://i38.photobucket.com/albums/e149/eloginko/profile_male_large_zpseedb2954.jpg');
background-position: -20px -10px;
width: 120px;
height: 120px;
display: inline-block;
}
The javascript is the same.
I wrote a quick little script to somewhat handle this:
JSFiddle: http://jsfiddle.net/LvsYc/3102/
$(function () {
var loader = 'http://i38.photobucket.com/albums/e149/eloginko/profile_male_large_zpseedb2954.jpg';
$('img[data-src]:not([src])').each(function () {
var $img = $(this).attr('src', loader),
src = $img.data('src'),
$clone = $img.clone().attr('src', src);
$clone.on('load', function () {
$img.attr('src', src);
});
});
});
Basically, here's what happens:
On load, iterate through all image tags that have a data-src but no src set.
Clone the img tag and set its src to the data-src.
Once the cloned img has loaded, set the original img tag's src to the data-src.
There are tons of ways to handle this scenario, and I'm sure there are better ones out there than this, but this should do the trick.
Handle the onError event for the image to reassign its source using JavaScript:
function imgError(image) {
image.onerror = "";
image.src = "/images/noimage.gif";
return true;
}
<img src="image.png" onerror="imgError(this);"/>
Or without a JavaScript function:
<img src="image.png" onError="this.onerror=null;this.src='/images/noimage.gif';" />

Vb.net fileupload preview image using javascript

I want to up load image using fileupload and preview the selected image before submit, but it can only work in firefox and IE6. I want to work in IE 7 8 and chrome, also it should work in firefox
<style type="text/css">
#newPreview
{
filter: progidXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale);
width: 136px;
height: 134px;
margin-left: 1px;
}
</style>
<script language="javascript" type="text/javascript">
function PreviewImg(imgFile) {
var newPreview = document.getElementById("newPreview");
var src;
if (document.all) {
newPreview.innerHTML = "<img src=\"file:///" + imgFile.value + "\" width=\"130px\">";
}
else {
newPreview.innerHTML = "<img src=\"" + imgFile.files.item(0).getAsDataURL() + "\" width=\"130px\">";
}
}
<form id="form1" runat="Server" method="post" enctype="multipart/form-data">
<div id="newPreview">
<asp:FileUpload ID="file" runat="server" size="20" Width="129px"
onchange="PreviewImg(this)"/>
Try like below.. Its working in FireFox and Chrome
It will help you...
CSS :
<style>
#imgPreview
{
filter: progidXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale);
width: 136px;
height: 134px;
margin-left: 1px;
}
</style>
Script:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function PreviewImg(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imgPreview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
HTML :
<asp:FileUpload ID="file" runat="server" size="20" Width="258px"
onchange="PreviewImg(this)"/>
<img id="imgPreview" src="#"/>

Categories