Show image preview until upload - javascript

I test this script, see here. But I can't do working, because when select image, only show codes no the image.
<script>
jQuery(document).ready(function(e){
jQuery('#file_input').change(function(e) {
//alert("okokok");
/**/
readFile(this.files[0], function(e) {
//manipulate with result...
jQuery('#output_field').text(e.target.result);
});
});
});
function readFile(file, callback){
var reader = new FileReader();
reader.onload = callback
reader.readAsText(file);
}
</script>
HTML Code :
> <input type="file" id="file_input" class="foo" /> <div
> id="output_field" class="foo"></div>
When select the file I want, only show encode words and numbers, not the image. I don't know how or why does this happen?

Try this code:
jQuery(document).ready(function(e){
jQuery('#file_input').change(function(e) {
//alert("okokok");
/**/
readFile(this.files[0], function(e)
{
//manipulate with result...
jQuery('#output_field').src(e.target.result);
});
});
});
function readFile(file, callback){
var reader = new FileReader();
reader.onload = callback
reader.readAsDataURL(file);
}
This assumes that #output_field is an image, otherwise you should change it to an img element.
This article can be helpful: http://www.javascripture.com/FileReader

Related

View and Hide Image Using Jquery

I am displaying images before upload using jquery, when i upload some new files i want to remove or hide the previous upload files here's my jquery code:
$(function()
{
// Multiple images preview in browser
var imagesPreview = function(input, placeToInsertImagePreview)
{
if (input.files)
{
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++)
{
var reader = new FileReader();
reader.onload = function(event)
{
$($.parseHTML('<img class="p-3" width="350px" height="250px">')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i]);
}
}
}
$('#file_input').on('change', function()
{
imagesPreview(this, 'div#viewUploadItems');
});
});
And my HTML Code:
<input type="file" name="images[]" id="file_input" class="deletable" multiple />
<div id="viewUploadItems"></div>
I try this code but this won't display any image.
$("#file_input").on("click",function()
{
$('input.deletable').val('');
$('#viewUploadItems').remove();
});
Perhaps you could take the following approach, where in your imagePreview() function you:
first call empty() on the preview selector to clear any prior image contents
then proceed to read and display any selected images, by using the FileReader API as you currently are (see below for revised approach)
Also, consider checking the type of the file object, to ensure that it is an image before attempting to display it via the following:
if (file.type.match("image.*")) {
/* file is image type, so attempt to preview it */
}
Bringing these ideas together, you could revise your code as follows:
$(function() {
function imagesPreview(input, targetSelector) {
/* Empty the target area where previews are shown */
$(targetSelector).empty();
/* Iterate each file via forEach in own closure */
Array.from(input.files).forEach(function(file) {
/* If file is image type proceed to preview */
if (file.type.match("image.*")) {
/* Create filereader and set it up for reading */
var reader = new FileReader();
reader.onload = function(event) {
/* Append a new image element, prepopulated with
required attrbutes, and assigned with p-3 class */
$(targetSelector).append($('<img>', {
width: '350px',
height: '250px',
src : reader.result
}).addClass('p-3'))
}
reader.readAsDataURL(file);
}
})
}
$('#file_input').on('change', function() {
imagesPreview(this, 'div#viewUploadItems');
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="file" name="images[]" id="file_input" class="deletable" multiple />
<div id="viewUploadItems"></div>
Easier to clear the div before display : $(placeToInsertImagePreview).html("");
$(function()
{
// Multiple images preview in browser
var imagesPreview = function(input, placeToInsertImagePreview)
{
if (input.files)
{
$(placeToInsertImagePreview).html("");
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++)
{
var reader = new FileReader();
reader.onload = function(event)
{
$($.parseHTML('<img class="p-3" width="350px" height="250px">')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i]);
}
}
}
$('#file_input').on('change', function()
{
imagesPreview(this, 'div#viewUploadItems');
});
});

When I insert a file in an input file it shows preview, but how to delete a selected file?

I got this javascript to show image preview when user select the file, it is working.
Case:
- If user select wrong image and delete it then preview do not refresh to 'empty'.
I have no idea how can I do this, already lookd around google and stackoverflow and nothing. Can someone give me a light please?
<img id="image1" width="300px" height="300px"/>
<img id="image2" width="300px" height="300px"/>
<img id="image3" width="300px" height="300px"/>
<img id="image4" width="300px" height="300px"/>
<script>
document.getElementById("productimage1").onchange = function () {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById("image1").src = e.target.result;
};
reader.readAsDataURL(this.files[0]);
};
document.getElementById("productimage2").onchange = function () {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById("image2").src = e.target.result;
};
reader.readAsDataURL(this.files[0]);
};
document.getElementById("productimage3").onchange = function () {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById("image3").src = e.target.result;
};
reader.readAsDataURL(this.files[0]);
};
document.getElementById("productimage4").onchange = function () {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById("image4").src = e.target.result;
};
reader.readAsDataURL(this.files[0]);
};
</script>
If I get what you want correctly...
You want the image preview to be cleared when user tries to select a new image using the "open file" window. No delete button.
Here is what you should do then:
// A delete function
$("[id^='product']").on("click",function(){
// This clears the input value.
$(this).val("");
// This resets the preview.
var imageID = $(this).attr("id").substr(7);
$("#"+imageID).attr("src","https://placehold.it/300x300");
});
See in CodePen
---EDIT
Here is the full code optimized.
// A delete function
$("[id^='product']").on("click",function(){
// This clears the input value.
$(this).val("");
// This resets the preview.
var imageID = $(this).attr("id").substr(7);
$("#"+imageID).attr("src","https://placehold.it/300x300");
});
// The preview function
$("[id^='product']").on("change",function(){
var imageID = $(this).attr("id").substr(7);
// Displays a preview im the right div
var reader = new FileReader();
reader.onload = function (e) {
$("#"+imageID).attr("src",e.target.result);
};
reader.readAsDataURL(this.files[0]);
});
See in CodePen - version #2

Display Image Preview instead of text [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
We are trying to upload an image to our site.
We click on "Upload Image" button.
Then it displays pop up box.
Then we click on Upload New image button
After that, we will select image from computer & displaying message Image uploaded
Instead of message "Image uploaded", i want to display preview of Uploaded image as like this Jsfiddle
code to display message "Image uploaded"
<input type="file" id="add_image_{{rand}}" class="newcustomimage" name="new_image" value=""/>
js
jQuery(document).ready(function () {
jQuery('body').delegate('.newcustomimage', 'change', function () {
if(jQuery(this).val()) {
jQuery(this).parent().parent().append('<div id="add_image_2508269_success" class="success-message validation-advice"> Image Uploaded.</div>');
}
});
});
I did below changes for above code to display "Image Preview" instead of message. Now Image preview is not displaying after we upload image. Instead its displaying like below image before we uploading an image in site.
<input type="file" id="add_image_{{rand}}" class="newcustomimage" name="new_image" value=""/>
<img id="blah" src="http://example.com/media/custom_product_preview/quote" />
Js
jQuery(document).ready(function () {
jQuery('body').delegate('.newcustomimage', 'change', function () {
if (jQuery(this).val()) {
jQuery(this).parent().parent().append('<div id="add_image_2508269_success" class="success-message validation-advice"> Image Uploded.</div>');
}
});
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]);
}
}
To do that please follow below
add this in your html
<input type="file" id="add_image_{{rand}}" data-rand={{rand}} class="newcustomimage" name="new_image" onchange="readURL(this);" value="" />
<img id="previewImg" src="#" style="display: none;height: 200px; width: 200px;" >
The java script for the same will be.
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
jQuery('#previewImg').attr('src', e.target.result);
jQuery('#previewImg').show();
}
reader.readAsDataURL(input.files[0]);
}
}
This will work in your case please have a try.
This seems to be working fine. Just need to configure the dimensions of the image.
Apply the following css:
.tool-body.selected {
text-align: center;
}
#previewImg {
height: 75px;
display: inline-block;
}
Also correct the spelling of uploaded.
EDIT
The following code works perfectly for the OP and meets his requirement:
jQuery(document).ready(function() {
jQuery('body').on('.newcustomimage', 'change', function() {
if (jQuery(this).val()) {
console.log(jQuery(this).val());
if (jQuery(this).val()) {
var reader = new FileReader();
}
jQuery(this).parent().parent().append('<div id="add_image_2508269_success" class="success-message validation-advice"> Image Uploaded.</div>');
}
});
jQuery(".aitcg-button").click(function() {
jQuery('#previewImg').hide();
});
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
jQuery('#previewImg').attr('src', e.target.result);
jQuery('#previewImg').show();
};
reader.readAsDataURL(input.files[0]);
}
}
The screengrab to the working site can be found here.
You can try like this
HTML
<input type="file" id="add_image_{{rand}}" class="newcustomimage" name="new_image" value=""/>
<div id="imgcontaner"></div>
JS
$(".newcustomimage").change(function() {
var input = this;
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$("#imgcontaner").empty();
$('<img/>').appendTo("#imgcontaner")
.attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
});
You have not called function on file select. You need to change it like this:
jQuery(document).ready(function (){
jQuery('body').delegate('.newcustomimage', 'change', function (){
if (jQuery(this).val())
{
readURL(jQuery(this));
}
});
});
keep there readurl function outside jQuery(document).ready
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
jQuery('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}

How to remove image preview when cleared?

I have a program where a selected image is previewed. Here is the code I use.
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]);
}
}
$("#uploadphoto").change(function(){
readURL(this);
$('#preview').show();
});
But when I remove it with this:
$('#preview').on("click", function () {
$('#uploadphoto').replaceWith( selected_photo = $('#uploadphoto').clone( true ) );
$('#preview').attr('src', '');
});
The photo still is displayed. When I submit the page the photo is not submitted, which I wanted, but how do I get rid of the preview image? $('#preview').attr('src', ''); didn't seem to work...?
You'd use removeProp() for that, as just changing the attribute isn't enough:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview').attr('src', e.target.result).show();
}
reader.readAsDataURL(input.files[0]);
}
}
$("#uploadphoto").change(function () {
readURL(this);
$('#preview').show();
});
$('#preview').on("click", function () {
$('#uploadphoto').replaceWith(selected_photo = $('#uploadphoto').clone(true));
$('#preview').removeProp('src').hide();
});
FIDDLE
You should also hide and show the image, to make sure the "empty image" icon doesn't show, or you could just remove the element all together and insert a new one each time.
EDIT:
To fade the image out, do:
$('#preview').on("click", function () {
$('#preview').fadeOut(1000, function() {
$(this).removeProp('src');
$('#uploadphoto').replaceWith(selected_photo = $('#uploadphoto').clone(true));
});
});

how to loop this function?

Thanks to some help on here I have a way of previewing images selected for and upload using:
<input type='file' name="files[]" onchange="readURL(this);" multiple />
<div id="previews"></div>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
var container = $('#previews');
var image = $('<img>').attr('src', e.target.result).width(150);
image.appendTo(container);
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
I was wondering how to loop this function for each file selected on the input? I just don't see where to use something like .each()
edit:
am trying this.. but its wrong somewhere, as it displays 2 previews but both of the same image?
function readURL(input) {
$.each(input.files,function(i) {
var reader = new FileReader();
reader.onload = function (e) {
var container = $('#previews');
var image = $('<img>').attr('src', e.target.result).width(150);
image.appendTo(container);
};
reader.readAsDataURL(input.files[0]);
});
}
input.files is a FileList, which acts like an array.
You can use jQuery.each on it like any other array.
You just need to loop over the last line, where the file is selected.
function readURL(input) {
var reader = new FileReader();
reader.onload = function (e) {
var container = $('#previews');
var image = $('<img>').attr('src', e.target.result).width(150);
image.appendTo(container);
};
$.each(input.files,function(i) {
reader.readAsDataURL(input.files[i]);
});
}

Categories

Resources