how to show thumbnails of dropped images before submit - javascript

<div class="top-main-section">
<%= form_for #usr_vendor_web_slide ,url:{action: "slidecreate"} , html: {class: "form-horizontal"} do |f| %>
<div class="top-main-section-area">
<div id="upload-area" class="uploader1" onclick="$('#post_image').click()">
<%= f.file_field :images, :onchange => 'readURL(this)', class:'slide-img', multiple: true, id:'slide-img'%>
<img id="slide_image" src="#" alt="image" style="display: none;" class="slide_image" />
</div>
</div>
<%= f.submit({:class => 'btn btn-primary'}) %>
<% end %>
</div>
<div id="thumbnail" class="thumbnail">
<img id="slide_image1" src="#" alt="" style="" />
</div>
javascript file
var data = [];
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
var ids = $("#slide_image");
insert();
function insert() {
var id;
id = ids;
data.push({
id: id,
});
clearAndShow()
}
function clearAndShow() {
// Clear our fields
ids = "";
console.log(data)
}
reader.onload = function(e) {
$("#slide_image").style.display = 'block';
$('#slide_image').attr('src', e.target.result).width(1000).height(480);
$("#slide_image").style.display = 'block';
$('#slide_image1').attr('src', e.target.result).width(100).height(100);
};
reader.readAsDataURL(input.files[0]);
}
}
I'm try to show images thumbnails before submit . I'll success in current dropped image show in top main section area and show it's thumbnail in thumbnail part. but i want to show all thumbnails in thumbnail part before submit. I'll try to make a javascript array and store images in that array. but i cannot get image src to show in thumbnail part. appreciate your ideas

function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById("slide_image").style.display = 'block';
$('#slide_image')
.attr('src', e.target.result)
.width(1000)
.height(480);
};
reader.readAsDataURL(input.files[0]);
}
}
window.onload = function() {
document.getElementById('files').addEventListener('change',
handleFileSelect, false);
function handleFileSelect(evt) {
console.log("hariii");
var files = evt.target.files;
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function (theFile) {
return function (e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML =
[
'<img style="height: 75px; border: 1px solid #000;
margin: 5px" src="',
e.target.result,
'" title="', escape(theFile.name),
'"/>'
].join('');
document.getElementById('thumbnail').insertBefore(span,
null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
}
this is my solution and it works fine for my proect

Showing Thumbnail preview for the images which user selected to upload will help user to make sure they are selected the right images. Here is the code which can show preview of images as thumbnail for the selected objects. You can try either selecting or drag and drop for previewing the images.
This code uses the HTML5 features and may not work with old browsers. The two main HTML5 features used by this code are FileReader and Canvas.
Javascript
jQuery(function($){
var fileDiv = document.getElementById("upload");
var fileInput = document.getElementById("upload-image");
console.log(fileInput);
fileInput.addEventListener("change",function(e){
var files = this.files
showThumbnail(files)
},false)
fileDiv.addEventListener("click",function(e){
$(fileInput).show().focus().click().hide();
e.preventDefault();
},false)
fileDiv.addEventListener("dragenter",function(e){
e.stopPropagation();
e.preventDefault();
},false);
fileDiv.addEventListener("dragover",function(e){
e.stopPropagation();
e.preventDefault();
},false);
fileDiv.addEventListener("drop",function(e){
e.stopPropagation();
e.preventDefault();
var dt = e.dataTransfer;
var files = dt.files;
showThumbnail(files)
},false);
function showThumbnail(files){
for(var i=0;i<files.length;i++){
var file = files[i]
var imageType = /image.*/
if(!file.type.match(imageType)){
console.log("Not an Image");
continue;
}
var image = document.createElement("img");
// image.classList.add("")
var thumbnail = document.getElementById("thumbnail");
image.file = file;
thumbnail.appendChild(image)
var reader = new FileReader()
reader.onload = (function(aImg){
return function(e){
aImg.src = e.target.result;
};
}(image))
var ret = reader.readAsDataURL(file);
var canvas = document.createElement("canvas");
ctx = canvas.getContext("2d");
image.onload= function(){
ctx.drawImage(image,100,100)
}
}
}
});
HTML
<input type="file" style="display:none" id="upload-image" multiple="multiple"></input>
<div id="upload" class="drop-area">
Upload File
</div>
<div id="thumbnail"></div>
CSS
.drop-area{
width:100px;
height:25px;
border: 1px solid #999;
text-align: center;
padding:10px;
cursor:pointer;
}
#thumbnail img{
width:100px;
height:100px;
margin:5px;
}
canvas{
border:1px solid red;
}

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');
});
});

pure-JavaScript drag images to browser

I am trying to un-jQuery-fy a clever piece of code, but one that is just a bit too clever.
The objective is simple. Drag images from the desktop to the browser.
During this unjQueryfication, I find that, lo and behold, a dollar-sign function is actually implemented in Chrome and Firefox. So even without including jQuery, it sort of works already.
Here is what I came up with so far. What am I missing?
var el = document.getElementById('holder');
function stop_and_prevent(e) {
e.stopPropagation();
e.preventDefault();
}
function load_images(files) {
var images = document.getElementById("images");
files.map(function(file) {
var reader = new FileReader();
reader.onload = function(event) {
if (file.type.match('image.*')) {
var img = document.createElement('img');
img.src = event.target.result;
images.appendChild(img);
reader.readAsDataURL(file);
}}
});
}
function onDrop(e) {
e.stop_and_prevent();
load_images(e.dataTransfer.files);
return false;
}
el.addEventListener('dragenter', stop_and_prevent, false);
el.addEventListener('dragover', stop_and_prevent, false);
el.addEventListener('dragleave', stop_and_prevent, false);
el.addEventListener('drop', onDrop, false);
div#holder {
border: 5px dashed #ccc;
height:400px;
width:400px;
font-family:Verdana;
text-align:center;
}
<div id="holder">
<p>Drag files here</p>
<div id="images"></div>
</div>
You probably meant to use:
stop_and_prevent(e);
in your drop handler instead of the current:
e.stop_and_prevent();
Also, since files is of type FileList and not Array you won't be able to use map() directly on it. Just use a normal loop or a [].forEach.call() instead.
You don't need to prevent events on the dragleave handler.
Updated code:
var el = document.getElementById('holder');
function stop_and_prevent(e) {
e.stopPropagation();
e.preventDefault();
}
function load_images(files) {
var images = document.getElementById("images");
[].forEach.call(files, function(file) {
if (file.type.match('image.*')) {
var reader = new FileReader();
reader.onload = function() {
var img = document.createElement('img');
img.src = this.result; //=reader.result, or use event.target.result
images.appendChild(img);
}
reader.readAsDataURL(file);
}
});
}
function onDrop(e) {
stop_and_prevent(e);
load_images(e.dataTransfer.files);
return false;
}
el.addEventListener('dragenter', stop_and_prevent);
el.addEventListener('dragover', stop_and_prevent);
el.addEventListener('drop', onDrop);
div#holder {
border: 5px dashed #ccc;
height:400px;
width:400px;
font-family:Verdana;
text-align:center;
}
<div id="holder">
<p>Drag files here</p>
<div id="images"></div>
</div>

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

preview image inside draggable jquery

is it possible to preview image before upload inside a draggable with knockout? I have some of the code but I cannot get it to work. I can type text and insert them inside a container but when I try to preview an image I cannot view the image alone I have to type a text before I can preview image. I would like to be able to preview as many images as possible at any given type without having to type any text before hand. if you need further explanation please feel free to ask thank you for your time.
this is html to upload text and image
<p align="center"><textarea data-bind="value: textContent" Placeholder="Type text to append" rows="4" cols="21"></textarea>
<button data-bind="click: addNew">Create</button></p>
<p align="center"><input type="file" id="files" name="file" multiple />
this is my html that displays the text and image
<div id="box" class="container">
<div data-bind="foreach:items" class="fix_backround">
<div href="#" class="item" data-bind="draggable:true,droppable:true">
<b><font face="Arial Black" color="red"><span data-bind="click:$parent.remove" style="font-size:12pt;">X</span></font></b><br/><br/>
<center><span class="text" data-bind="text:$data"></span><input class="edit_text"/></center>
this is where the image is shown
<output id="list"></output>
this is my image script
function handleFileSelect(evt) {
var files = evt.target.files;
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML =
[
'<img style="height: 150px; border: 1px solid #000; margin: 5px" src="',
e.target.result,
'" title="', escape(theFile.name),
'"/>'
].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
this is my draggable script
var z = 1; //value to make div overlappable
$('#addText').click(function (e) {
/** Make div draggable **/
$('<div />', {
class: 'ui-widget-content',
appendTo: '.container',
draggable: {
containment: 'parent',
start: function( event, ui ) {
$(this).css('z-index', ++z);
}
}
});
});
$(document).on("dblclick", '.text', function()
{
$(this).hide(); $(this).closest('.item').find('.edit_text').val ($(this).text()).show();
});
$(document).on("click", ".edit_text", function()
{
return false;
});
$(document).on("click", function()
{
var editingText = $('.edit_text:visible');
if (editingText.length)
{
editingText.hide();
editingText.closest('.item').find('.text').text($(editingText).val()).show();
}
});
var count = 1;
var selectedDraggable;
ko.bindingHandlers.draggable={
init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
$(element).draggable();
$(element).addClass('item' + count);
count++;
$(element).on('click', function () {
selectedDraggable = $(this);
})
}
};
var vm=function(){
var self=this;
self.items=ko.observableArray();
self.textContent = ko.observable('');
self.init=function(){
self.items([]);
}
self.remove=function(item){
console.log(item);
self.items.remove(item);
}
self.addNew = function() {
self.items.push( self.textContent() );
self.textContent('');
}
self.init();
}
ko.applyBindings(new vm());

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