Javascript getElementById but keep old value - javascript

I have a file_field_tag inside a rails form with a select file field:
<%= file_field_tag "attachments[media_files][]", multiple: true, id: "files" %>
And I have an area to preview the images/videos and remove if need be:
<span id="result"></span>
Everything is working correct but there is only one glitch.... If the images/videos are in separate folders, I have to add the files from one folder first and then from the other folder. The files show at the preview, but after this process only the second batch of files gets saved when I submit the form.
Here is the javascript for all of the above:
window.onload = function(){
if(window.File && window.FileList && window.FileReader)
{
var filesInput = document.getElementById("files");
filesInput.addEventListener("change", function(event){
var files = event.target.files;
var output = document.getElementById("result");
for(var i = 0; i< files.length; i++)
{
var file = files[i];
if (!file.type.match(/.(jpg|jpeg|png|gif|mp4|avi|flv|wmv|mov|tiff|bmp|exif)$/i))
continue;
var picReader = new FileReader();
picReader.addEventListener("load",function(event){
var picFile = event.target;
var span = document.createElement("span");
span.innerHTML = ['<img class="thumb" src="', picFile.result, '" title="', picFile.name, '"/><span class="remove_img_preview"></span>'].join('');
output.insertBefore(span,null);
span.children[1].addEventListener("click", function(event){
span.parentNode.removeChild(span);
});
});
picReader.readAsDataURL(file);
}
});
}
else
{
console.log("Your browser does not support File API");
}
}

Depending on what you're trying to achieve you could just save the files into an array variable:
////////////////////////////////
// Create an array for the files somewhere
var fileCache = [];
////////////////////////////////
window.onload = function(){
if(window.File && window.FileList && window.FileReader)
{
var filesInput = document.getElementById("files");
filesInput.addEventListener("change", function(event){
var files = event.target.files;
var output = document.getElementById("result");
for(var i = 0; i< files.length; i++)
{
var file = files[i];
if (!file.type.match(/.(jpg|jpeg|png|gif|mp4|avi|flv|wmv|mov|tiff|bmp|exif)$/i))
continue;
////////////////////////////////
// Add each file to the array as you process it
fileCache.push(file);
////////////////////////////////
var picReader = new FileReader();
picReader.addEventListener("load",function(event){
var picFile = event.target;
var span = document.createElement("span");
span.innerHTML = ['<img class="thumb" src="', picFile.result, '" title="', picFile.name, '"/><span class="remove_img_preview"></span>'].join('');
output.insertBefore(span,null);
span.children[1].addEventListener("click", function(event){
span.parentNode.removeChild(span);
});
});
picReader.readAsDataURL(file);
}
});
}
else
{
console.log("Your browser does not support File API");
}
}
<input type="file" id="files" />
Generally, I would avoid using a random global variable, but without knowing exactly what you want to do with the list of files this is the most generic answer.

Related

Preview images before uploading using JavaScript not working in Microsoft Edge

Here is my code that I have used for image previewing before uploading. This code works perfectly in other browsers like Chrome, IE, Safari but not in Edge, specifically for .PNG images. Please help me out. The problem is first time it is not showing any preview but if I upload JPG and then PNG image only then the PNG image preview is shown.
function readURL(input,id) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#'+id).attr('src', e.target.result)
}
reader.readAsDataURL(input.files[0]);
}
}
Try the following might help
window.onload = function() {
if (window.File && window.FileList && window.FileReader) {
var filesInput = document.getElementById("uploadImage");
filesInput.addEventListener("change", function(event) {
var files = event.target.files;
var output = document.getElementById("result");
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.type.match('image'))
continue;
var picReader = new FileReader();
picReader.addEventListener("load", function(event) {
var picFile = event.target;
var div = document.createElement("div");
div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" +
"title='" + picFile.name + "'/>";
output.insertBefore(div, null);
});
picReader.readAsDataURL(file);
}
});
}
}
<input type="file" id="uploadImage" name="termek_file" class="file_input" multiple/>
<div id="result" class="uploadPreview">

How to load image from directory, then show onclick

I am trying to have a function which has functions that do the following.
One function to store the files i get with input into the parent functions loadedimages array(loadimages).
One function to show those files in the correct component(showLoadedImages).
And one function to make the correct img file appear on the correct component.
The last function is what i want it to be like(it does not work).
The other two seem ok.
The problem i have is how to make the last function work while using the loadedimages array. You can change what i store in the array , i wouldnt mind.
Here is the JS code:
function imgviewer() {
"use strict";
var loadedimages = [];
var lidivs = [];
function loadimages() {
var files = document.getElementById("images").files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.name.match(/\.(jpg|jpeg|png|gif)$/)) {
alert('THERE IS NO IMAGE IN THIS DIRECTORY.');
break;
}
loadedimages.push(file);
}
}
function showLoadedImages(elem) {
loadimages();
var ld = loadedimages;
//var files = getLoadedImages(); //filelist obj
for (var i = 0; i < ld.length; i++) {
var file = ld[i];
var reader = new FileReader();
reader.onload = (function(file) {
return function(e) {
// Render thumbnail.
var span = document.createElement(
'span');
span.innerHTML = [
'<img class="tile" src="',
e.target.result,
'" title="', encodeURI(
file.name), '">'
].join('');
document.getElementById(elem).insertBefore(
span, null);
lidivs.push(span);
};
})(file);
// Read in the image file as a data URL.
reader.readAsDataURL(file);
}
}
function showImage(index, elem) {
var chosenFile = loadedimages[index];
document.getElementById(elem).src = chosenFile;
}
document.getElementById('images').addEventListener('change', function(){
showLoadedImages("main");
}, false);
}
And some HTML
<form name="uploadForm">
<input id="images" type="file" webkitdirectory mozdirectory directory name="myFiles"
multiple/>
<span id="list"></span>
</form>
<div id="sidebar1"><img id="willchange" src="images/railaythailand.jpg" width="1200" height="832" alt=""/></div>
<div id="main"></div>
When i call showLoadedImages("main") the images are shown in main div. I want to be able to click those images so that they appear on "willchange" .
This does what you asked for. There are a number of other issues with your code that you might want to address, starting with the images are not thumbnails at all (and shrunken images take just as long to load as the original), but perhaps I'm missing something.
"use strict";
var loadedimages = [];
var lidivs = [];
function loadimages() {
var files = document.getElementById("images").files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.name.match(/\.(jpg|jpeg|png|gif)$/)) {
continue;
}
loadedimages.push(file);
}
loadedimages.length || alert('THERE IS NO IMAGE IN THIS DIRECTORY.');
}
function showLoadedImages(elem) {
loadimages();
var ld = loadedimages;
//var files = getLoadedImages(); //filelist obj
for (var i = 0; i < ld.length; i++) {
var file = ld[i];
var reader = new FileReader();
reader.onload = (function(file) {
return function(e) {
// Render thumbnail.
var span = document.createElement(
'span');
span.innerHTML = [
'<img data-index="',
lidivs.length,
'" class="tile" src="',
e.target.result,
'" title="', encodeURI(
file.name), '">'
].join('');
span.addEventListener("click", foo );
document.getElementById(elem).insertBefore(
span, null);
lidivs.push(span);
};
})(file);
// Read in the image file as a data URL.
reader.readAsDataURL(file);
}
}
function showImage(index, elem) {
document.getElementById(elem).src = lidivs[index].children[0].src;
}
function foo(event) {
showImage(event.target.dataset.index, "willchange");
}
function show() {
showLoadedImages("list");
}
function init() {
document.getElementById("images").addEventListener("change", show, false);
}
document.addEventListener( "DOMContentLoaded", init, false );
<body>
<form name="uploadForm">
<input id="images" type="file" webkitdirectory mozdirectory directory name="myFiles"
multiple/>
<span id="list"></span>
</form>
<div id="sidebar1"><img id="willchange" src="images/railaythailand.jpg" width="1200" height="832" alt=""/></div>
</body>

How can we upload multiple html files and replace the text inside and get the output html pages with the help of javascript

From following code it accepts Single File and process it & display output.but can it be possible to accept multiple files and process & then return output.
<html>
<head>
</head>
<body>
<div>
<label for="text">Choose file</label>
<input id="text" type="file" name="photo">
</div>
<textarea id="finalHTML" style="height:200px;width:80%">
</textarea><br/>
<button id="save">Save</button>
<script>
$('input').change(function(){
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
console.log(e);
selectedImage = e.target.result;
var rawData = reader.result;
console.log(rawData);
var array = {
'<code CLASS="java">j</code>':'⇔',
'<code CLASS="bold">C</code>':'<b>C</b>',
'<code CLASS="italic">g</code>':'œ',
'<code CLASS="underline">i</code>':'~',
}
var originalText = rawData.toString();
var finalText = originalText;
for (var val in array)
finalText = finalText.replace(new RegExp(val, "g"), array[val]);
console.log(finalText);
$('#finalHTML').text(finalText);
};
reader.readAsBinaryString(this.files[0]);
//reader.readAsDataURL(this.files[0]);
}
});
var button2 = document.getElementById('save');
button2.addEventListener('click', saveTextAsFile);
function saveTextAsFile()
{
var textToWrite = $('#finalHTML').text();
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
var fileNameToSaveAs = "sample1.html"/*Your file name*/;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
if (window.webkitURL != null)
{
// Chrome allows the link to be clicked
// without actually adding it to the DOM.
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
}
else
{
// Firefox requires the link to be added to the DOM
// before it can be clicked.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
</script>
</body>
</html>
I am not able to accept multiple files and process on it,and return Output.
Any one can help me out please.
You used input type 'file' there is an attribute multiple ="multiple" which allows you to select multiple file at once. How to handle those files using JavaScript? you can look at this link ...Multiple-files-selected
try this and look at the for loop block... I'm not tasted it...
$('input').change(function(){
for(var i = 0; i<= files.length; i++){
if (this.files && this.files[i]) {
var reader = new FileReader();
reader.onload = function (e) {
console.log(e);
selectedImage = e.target.result;
var rawData = reader.result;
console.log(rawData);
var array = {
'<code CLASS="java">j</code>':'⇔',
'<code CLASS="bold">C</code>':'<b>C</b>',
'<code CLASS="italic">g</code>':'œ',
'<code CLASS="underline">i</code>':'~',
}
var originalText = rawData.toString();
var finalText = originalText;
for (var val in array)
finalText = finalText.replace(new RegExp(val, "g"), array[val]);
console.log(finalText);
$('#finalHTML').text(finalText);
};
reader.readAsBinaryString(this.files[i]);
//reader.readAsDataURL(this.files[0]);
}
}
});

HTML5 multiple images selection limit and edit

I am trying to get a multiple image previewer where the limit is 5 selections, and if I want to change one of my selections, I click the x on that image and re-select a new image
My code right now shows an alert but still allows the selection afterwards. Please help!
DEMO
<input type="file" id="files" name="image_file_arr[]" multiple>
<br><output id="list"></output>
script:
$(function() {
$("input#files[type='file']").change(function(){
var $fileUpload = $("input#files[type='file']");
if (parseInt($fileUpload.get(0).files.length)>6){
alert("You can only upload a maximum of 5 files");
return false;
}
});
});
function handleFileSelect(evt) {
var files = evt.target.files;
for (var i = 0, f; f = files[i]; i++) {
if (!f.type.match('image.*')) { continue; }
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result, '" title="', escape(theFile.name), '"/>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
See this working fiddle http://jsfiddle.net/3D6pd/1/
Just put
var $fileUpload = $("input#files[type='file']");
if (parseInt($fileUpload.get(0).files.length)>6){
alert("You can only upload a maximum of 5 files");
return false;
}
this code inside the handleFileSelect function and use evt.stopPropagation();
this is updated fiddle try http://jsfiddle.net/3D6pd/6/
I have added a form and a submit button here,
$("#sub").click(function(e){
e.preventDefault();
alert("files uploaded="+ $("input#files[type='file']").get(0).files.length);
});
var count=0;
hope this helps
I have added this to your fiddle
$(function() {
var array=[];
$("#sub").click(function(e){
e.preventDefault();
$("input#files[type='file']").get(0).files=array;
alert("files uploaded="+ $("input#files[type='file']").get(0).files.length);
});
var count=0;
// Preview should only have up to 5 images
// onclick x, preview of that image should be deselected and removed from the preview screen
function handleFileSelect(evt) {
var $fileUpload = $("input#files[type='file']");
count=count+parseInt($fileUpload.get(0).files.length);
if (parseInt($fileUpload.get(0).files.length)>6 || count>5){
alert("You can only upload a maximum of 5 files");
count=count-parseInt($fileUpload.get(0).files.length);
evt.preventDefault();
evt.stopPropagation();
return false;
}
var files = evt.target.files;
array = array.concat(files);
for (var i = 0, f; f = files[i]; i++) {
if (!f.type.match('image.*')) { continue; }
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result, '" title="', escape(theFile.name), '"/><span class="remove_img_preview">x</span>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
});

Get full path image into input file

I want get the full path image from input file for show image preview and use for example attr of jquery for insert this into scr to this temporal image path , for example i think in that
var filePath = $(this).val();
console.log(filePath);
jQuery('#preview').attr("src",""+img_p);
The problem i don´t know how i can get this temporal path from input file for show and insert this path for the preview image until send to upload in the system
Thank´s , Regards
MOZILLA DEVELOPER NETWORK show us an example to do that:
<input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)">
Select some files
<div id="fileList">
<p>No files selected!</p>
</div>
<script>
window.URL = window.URL || window.webkitURL;
var fileSelect = document.getElementById("fileSelect"),
fileElem = document.getElementById("fileElem"),
fileList = document.getElementById("fileList");
fileSelect.addEventListener("click", function (e) {
if (fileElem) {
fileElem.click();
}
e.preventDefault(); // prevent navigation to "#"
}, false);
function handleFiles(files) {
if (!files.length) {
fileList.innerHTML = "<p>No files selected!</p>";
} else {
var list = document.createElement("ul");
for (var i = 0; i < files.length; i++) {
var li = document.createElement("li");
list.appendChild(li);
var img = document.createElement("img");
img.src = window.URL.createObjectURL(files[i]);
img.height = 60;
img.onload = function(e) {
window.URL.revokeObjectURL(this.src);
}
li.appendChild(img);
var info = document.createElement("span");
info.innerHTML = files[i].name + ": " + files[i].size + " bytes";
li.appendChild(info);
}
fileList.appendChild(list);
}
}
</script>
HERE the Mozilla DOC.
HERE some problem to do that.

Categories

Resources