I have an image upload preview. And, when user click in .thumb, I want to clone the input text name and show this. But clone()isn't working.
thanks
JSFIDDLE
HTML
<input type="file" id="files" name="files[]" multiple /><br />
<output id="list"></output><br />
<p>Name:<input type="text" class="name"/><p>
<br />
JS
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// 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 class="thumb" 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);
$('.thumb').click(function() {
$('p').clone();
});
I think this will do what you want to do. I don't know what you were doing with the .click, but I moved the HTML to your loop that generates the thumbs.
Fiddle: http://jsfiddle.net/howderek/emTAX/17/
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
$('.name').clone().appendTo(".name");
// 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 class="thumb" src="' + e.target.result + '" title="' + escape(theFile.name) + '"/><p>Name:<input type="text" class="name" /></p>');
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);
what about this..
im still confused about what you want to do.. but the click event wasnt working due to the image not being there when the dom was ready, after the fact
http://jsfiddle.net/emTAX/25/
$('body').on("click",".thumb",function() {
var myclone = $("p input").clone();
$('p:first').append(myclone);
});
append() is faster than appendTo()
basically using on() will keep the event listening for the .thumb and then attach the event on it
http://api.jquery.com/on/
Related
I'm trying to upload a file and convert that file to its data-uri counterpart without needing any sort of back-end, but I'm stuck at trying to figure out how to actually get the uploaded file.
document.getElementById("myInput").files[0]
allows me to access some information, but not the actual file. There's the file api, but I can't find much documentation about how to use it, just that it exists.
Is there any way to do this entirely in the browser?
Here's a code for multiple file input. You can do it for a single file by removing loop.
This will take the file as soon as you select file and displays inside the selected img tag
HTML Code
<div>
<img id="img-1" src="#" />
</div>
<div>
<img id="img-2" src="#"/>
</div>
Javascript Code
function readURL(input) {
if (input.files && input.files[0]) {
var countFiles = input.files.length;
for (var i = 0; i < countFiles; i++) {
// console.log(input.files);
if(i === 0) {
// console.log(input.files);
var reader = new FileReader();
reader.onload = function (e) {
// console.log(e);
$('#img-1')
.attr('src', e.target.result)
.width(135)
.height(135);
};
reader.readAsDataURL(input.files[i]);
}else if(i === 1) {
var reader = new FileReader();
reader.onload = function (e) {
// console.log(e);
$('#img-2')
.attr('src', e.target.result)
.width(135)
.height(135);
};
reader.readAsDataURL(input.files[i]);
}
}
}
}
I am trying to create a PHP file uploader with file preview before uploading. The script below works on multiple file upload for images only but would like to have an image icon for non-images with an image in the directory saying: "File preview not available."
// JavaScript Document
$(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>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i]);
}
else{
$($.parseHTML('<img>')).attr('src', '/assets/img/no_preview.png');
$('.imagepreview').attr('src', '../img/no_preview.png');
}
}
};
$('#prescription-photo-add').on('change', function() {
imagesPreview(this, 'div.prescription');
});
});
You can first check the file extension first. Then display the image of the file if it is an image and display "File preview not available." otherwise
Codes can be found in this answer
I'm using the following javascript inside my rails 5 app in order to preview the image before the form gets submitted.
The image form field has a setup for multiple files, but the javascript has a setup for only one. I can preview more then one image but eventually only one gets uploaded.
How can I make this javascript preview and upload multiple images?
<script>
function handleFileSelect(event)
{
console.log(event)
var input = this;
if (input.files && input.files[0])
{
var reader = new FileReader();
console.log(reader)
reader.onload = (function (e)
{
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="',e.target.result, '" title="', escape(e.name), '"/><span class="remove_img_preview"></span>'].join('');
document.getElementById('preview').insertBefore(span, null);
});
reader.readAsDataURL(input.files[0]);
}
}
//su kien thay doi hinh khac
$('#files').change(handleFileSelect);
//day la su kien click vao nut x để xóa ảnh
$('#preview').on('click', '.remove_img_preview',function ()
{
$(this).parent('span').remove();
$(this).val("");
});
</script>
how can I with a input text field with a button, let the user pick a .txt file from harddrive and also give the option of storing content from the text field onto harddrive, when using Chrome.
How can I do that with pure Javascript?
Kindest regards
/Lasse
Try using input type="file" with accepts MIME type set to "text/plain", textarea , a element , download attribute , FileReader , data: protocol , encodeURIComponent
var input = document.querySelector("input");
var text = document.querySelector("textarea");
var button = document.querySelector("button");
var name;
input.onchange = function() {
name = this.files[0].name;
var reader = new FileReader();
reader.onload = function() {
text.value = this.result
}
reader.readAsText(this.files[0])
}
button.onclick = function() {
var a = document.createElement("a");
// `"data:text/plain," + text.value` : new file
a.href = "data:text/plain;charset=utf-8," + encodeURIComponent(text.value);
a.download = name || "file-" + new Date().getTime();
document.body.appendChild(a);
// creates `"Save file"` dialog
a.click();
document.body.removeChild(a)
}
<input type="file" accepts="text/plain"/><br>
<textarea width="300px" height="200px">
</textarea><br>
<button>save</button>
A full answer to your question would be very lengthy, so briefly:
Use a form with an input that is type file that allows the user to input a file:
<form>Select file: <input type="file" id="loadfile"/></form>
Using javascript, react to the value being set by listening to either the submit event, the click event, or the change event. The example here looks at the change event.
var input = document.getElementById('loadfile');
input.onchange = function handleInputFileChanged(event) {
var files = event.target.files;
if(!files || !files.length) {
return;
}
importFiles(files);
};
function importFiles(files) {
// Read in the contents of the files as text and process them here
var numFiles = files.length;
var filesProcessed = 0;
for(var i = 0; i < numFiles; i++) {
processFile(files[i]);
}
function processFile(file) {
var reader = new FileReader();
reader.onload = function() {
filesProcessed++;
// do something with the file text, here i am just printing
// it to the browser console
var contentString = reader.result;
console.log('File text: %s', contentString);
if(filesProcessed === numFiles) allFilesRead();
};
reader.onerror = function() {
filesProcessed++;
if(filesProcessed === numFiles) allFilesRead();
};
reader.readAsText(file);
}
function allFilesRead() {
// do something now that all files have been read
}
}
To save to a file, this can be done simply by providing the user a prompt. For example:
<form><button id="savebutton" value="Save"></form>
In script, listen for the button click event, and then initiate a download:
var button = document.getElementById('savebutton');
button.onclick = function(event) {
var content = getContentToSaveAsString();
// to automatically start a download, we are going to create a
// hidden anchor element, then pseudo-click it
// Create the anchor and sets its href to a data uri
var anchor = document.createElement('a');
var blob = new Blob([content], {type: 'text/plain'});
var objectURL = URL.createObjectURL(blob);
anchor.href = objectURL;
anchor.setAttribute('download', 'defaultfilenamegoeshere.txt');
// attach the hidden anchor to the page
anchor.style.display = 'none';
document.body.appendChild(anchor);
// this starts the download, the user will get a prompt of where to
// save or if in chrome it just starts downloading to download
// folder, just as if they had right clicked on an anchor in
// the page and selected Save Target As
anchor.click();
// remove our temporary anchor element, cleaning up after ourselves
URL.revokeObjectURL(objectURL);
anchor.remove();
};
function getContentToSaveAsString() {
// Create and return a string here that will be saved to a
// text file when the user clicks the save button
return 'string of stuff';
}
I have a problem with this code:
function handleFileSelect(evt) {
evt.stopPropagation();
evt.preventDefault(); // stop default
console.log('ejecutado handleFileSelects')
var divOrigen = evt.target.parentNode; //get the div of the input
var divDestino = $(divOrigen).find('img'); //get the div for preview the img
var inputDestino = $(divOrigen).find('input[type="file"]'); // the input file
var files = evt.target.files; //get files in array
if (files.length) {
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) {
$(divDestino).attr('src', e.target.result); //read files content to preview in div
};
})(f);
reader.readAsDataURL(f);
}
$(inputDestino).popover('destroy');
} else {
evt.stopPropagation();
evt.preventDefault();
$(inputDestino).popover('show');
console.log('files is empty');
$(divDestino).attr('src', '/images/index/publicacion/dragAndDropHere.png');
}
}
This code changes the background of a div. The purpose of the div is to preview the image of the input file. In Opera, Firefox, Internet Explorer and Safari it works fine, but when I try it on my Android tablet, nothing happens. Is there a tool similar to Firebug for Android? Or any framework that I can use for Android tablets?
Try removing the first / from the image source, so instead of
$(divDestino).attr('src', '/images/index/publicacion/dragAndDropHere.png');
you have
$(divDestino).attr('src', 'images/index/publicacion/dragAndDropHere.png');