JS read image and show - javascript

function handleFileSelect(evt) {
var files = evt.target.files;
for (var i = 0, f; i<2 ; i++){
f = files[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('pic'+i).insertBefore(span, null);
};
})(f,i);
reader.readAsDataURL(f);
}
}
I have this script from HERE, EXAMPLE 3 and i am trying to put every file in different place.
<tr><td colspan="2"><input type="file" id="inputFilesID" multiple ></td></tr>
<tr><td>Front</td><td><output id="pic0" /></td></tr>
<tr><td>Back</td><td><output id="pic1" /></td></tr>
For example, if that is mine html, why if i put 2 images my script trying to put everything at:
<tr><td>Bottom</td><td><output id="pic2" /></td></tr>

//Logic in Scripts.js
var canvas = document.getElementById('our-canvas'),
context = canvas.getContext('2d');
uploadedFile = document.getElementById('uploaded-file');
window.addEventListener('DOMContentLoaded',initImageLoader) ;
function initImageLoader(){
uploadedFile.addEventListener('change',handleManualUploadedFiles);
function handleManualUploadedFiles(ev){
var file = ev.target.files[0];
handleFile(file);
}
}
function handleFile(file){
var ImageType = /image.*/;
if(file.type.match(ImageType)){
var reader = new FileReader();
reader.onloadend = function(event){
var tempImageStore = new Image();
tempImageStore.onload = function(ev){
canvas.height = ev.target.height;
canvas.width = ev.target.width;
context.drawImage(ev.target,0,0);
}
tempImageStore.src = event.target.result;
}
reader.readAsDataURL(file);
}
}
//Showing in HTML
<b>our image canvas </b>
<input type="file" id="uploaded-file" />
<canvas id= "our-canvas" class="image-container"> </canvas>
<script src="scripts.js" > </script>

use npm jimp
============================
Jimp.read('./path/to/image.jpg')
.then(image => {
console.log(image.bitmap)//having the image buffer data,width,height ...etc
// Do stuff with the image.
})
.catch(err => {
// Handle an exception.
});

Related

Condition of filesize cause base 64 string to be gone?

Based on my previous post How can I convert an image into Base64 string from an image source? i would like to set my image file to have a size limit but however i couldnt get it to work if i set with a condition?
here the code below
function encodeImageFileAsURL() {
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("output").src = newImage.src;
alert("Converted Base64 version is " + document.getElementById("output").src);
console.log("Converted Base64 version is " + document.getElementById("output").src);
}
fileReader.readAsDataURL(fileToLoad);
}
}
var uploadField = document.getElementById("inputFileToLoad");
uploadField.onchange = function() {
// 1000000 = 1MB
if (this.files[0].size > 1000000) {
alert("File is too big!");
this.value = "";
} else if (this.files[0].size < 100000) {
alert("File not recommended size!");
this.value = "";
}
};
$('#inputFileToLoad').change(function(event) {
if(event.target.files[0]){
// var tmppath = URL.createObjectURL(event.target.files[0]);
$("img#output").fadeIn("fast").attr('src',URL.createObjectURL(event.target.files[0]));
}else{
alert('Image size mismatched.')
}
// $("#disp_tmp_path").html("Temporary Path(Copy it and try pasting it in browser address bar) --> <strong>["+tmppath+"]</strong>");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />
<img src="https://mdbootstrap.com/img/Photos/Others/placeholder-avatar.jpg" id="output" width="100" height="100" style="border-radius: 50%;" />
If i have my condition my data of base 64 dont show anymore how can i fix this issue ?
The code in the question has three separate event handlers for onchange of #inputFileToLoad. There is one declared on the element in the HTML which calls encodeImageFileAsURL(). This is then overwritten on line 25 with uploadField.onchange = function() { preventing encodeImageFileAsURL() from being called. A further onchange handler is then added on line 36 with $('#inputFileToLoad').change(function(event) {.
You could place all of this logic in a single event handler for onchange. This allows you to order the logic as you wish, also you can return if there is an issue (e.g. file size too large) preventing the remaining code from executing.
In the example below I have:
Added the event to be passed as a parameter to encodeImageFileAsURL(event) in the HTML onchange="encodeImageFileAsURL(event);
Moved the code from the various event handlers into the encodeImageFileAsURL function, changing references of this to event.target.
Added some return statements if the file size checks fail to prevent the remaining code from executing
Example is below,
function encodeImageFileAsURL(event) {
// File Size Checks
if (event.target.files[0].size > 1000000) {
alert("File is too big!");
event.target.value = "";
return;
} else if (event.target.files[0].size < 100000) {
alert("File not recommended size!");
event.target.value = "";
return;
}
// Update image on page
if (event.target.files[0]) {
// var tmppath = URL.createObjectURL(event.target.files[0]);
$("img#output").fadeIn("fast").attr('src', URL.createObjectURL(event.target.files[0]));
} else {
alert('Image size mismatched.')
return;
}
// Base64 conversion
var filesSelected = event.target.files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("output").src = newImage.src;
alert("Converted Base64 version is " + document.getElementById("output").src);
console.log("Converted Base64 version is " + document.getElementById("output").src);
}
fileReader.readAsDataURL(fileToLoad);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL(event);" />
<img src="https://mdbootstrap.com/img/Photos/Others/placeholder-avatar.jpg" id="output" width="100" height="100" style="border-radius: 50%;" />

JavaScript, csv to json, split is not a function [duplicate]

I want to show contents of uploaded file in html, I can just upload a text file.
My example.html:
<html xmlns="http://www.w3.org/1999/xhtml" >
<p>
Please specify a file, or a set of files:<br>
<input type="file" name="datafile" size="40">
</p>
<textarea id="2" name="y" style="width:400px;height:150px;"></textarea>
</html>
How can I show contents of any uploaded text file in textarea shown below?
I've came here from google and was surprised to see no working example.
You can read files with FileReader API with good cross-browser support.
const reader = new FileReader()
reader.onload = event => console.log(event.target.result) // desired file content
reader.onerror = error => reject(error)
reader.readAsText(file) // you could also read images and other binaries
See fully working example below.
document.getElementById('input-file')
.addEventListener('change', getFile)
function getFile(event) {
const input = event.target
if ('files' in input && input.files.length > 0) {
placeFileContent(
document.getElementById('content-target'),
input.files[0])
}
}
function placeFileContent(target, file) {
readFileContent(file).then(content => {
target.value = content
}).catch(error => console.log(error))
}
function readFileContent(file) {
const reader = new FileReader()
return new Promise((resolve, reject) => {
reader.onload = event => resolve(event.target.result)
reader.onerror = error => reject(error)
reader.readAsText(file)
})
}
label {
cursor: pointer;
}
textarea {
width: 400px;
height: 150px;
}
<div>
<label for="input-file">Specify a file:</label><br>
<input type="file" id="input-file">
</div>
<textarea id="content-target"></textarea>
Here's one way:
HTML
<tr>
<td>Select a File to Load:</td>
<td><input type="file" id="fileToLoad"></td>
<td><button onclick="loadFileAsText()">Load Selected File</button><td>
</tr>
JavaScript
function loadFileAsText(){
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent){
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
Try this.
HTML
<p>
Please specify a file, or a set of files:<br>
<input type="file" id="myFile" multiple size="50" onchange="myFunction()">
</p>
<textarea id="demo" style="width:400px;height:150px;"></textarea>
JS
function myFunction(){
var x = document.getElementById("myFile");
var txt = "";
if ('files' in x) {
if (x.files.length == 0) {
txt = "Select one or more files.";
} else {
for (var i = 0; i < x.files.length; i++) {
txt += (i+1) + ". file";
var file = x.files[i];
if ('name' in file) {
txt += "name: " + file.name + "";
}
if ('size' in file) {
txt += "size: " + file.size + " bytes ";
}
}
}
}
else {
if (x.value == "") {
txt += "Select one or more files.";
} else {
txt += "The files property is not supported by your browser!";
txt += "The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
}
}
document.getElementById("demo").innerHTML = txt;
}
Demo

Html & js not showing image

So the problem is that I want to create an img element with the same src as the insert file but its not working and I dont know why, here is the code:
<!DOCTYPE html>
<html>
<head>
<title>HMM...</title>
</head>
<body>
<input type="file" id="wowo">
<div id="dispImg">
</div>
<button onclick="wp()">run</button>
<script>
window.URL = window.URL || window.webkitURL;
function wp() {
var file = document.getElementById("wowo").value;
var nopath = file.substring(12);
alert(nopath);
var crimg = document.createElement("img");
crimg.src = window.URL.createObjectURL(nopath);
crimg.height = 60;
crimg.onload = function() {
window.URL.revokeObjectURL(this.src);
}
document.getElementById("dispImg").appendChild(crimg);
}
</script>
</body>
</html>
Thank you.
You can try this code:
function wp() {
var files = document.getElementById("wowo").files;
// FileReader support
if (FileReader && files && files.length) {
var crimg = document.createElement("img");
var fr = new FileReader();
fr.onload = function () {
crimg.src = fr.result;
}
fr.readAsDataURL(files[0]);
crimg.height = 60;
document.getElementById("dispImg").appendChild(crimg);
}
}
This is a demo https://jsbin.com/qaqoveq

How do I delete an image from a file input by clicking an "x" on an image preview?

I currently have a file input that shows an image preview once the user uploads their images. On the image preview, there is an "x" that removes the image preview from the list. Is there any way to remove the image from the set of files in the input once this "x" is clicked?
<label for="my_file_upload[]">
<span class="btn">Add Images</span>
</label>
<input style="visibility: hidden; position: absolute;" class="imagefet" type="file" name="upload_attachment[]" id="my_file_upload[]" multiple="multiple">
<br><output id="list"></output>
<script type="text/javascript">
jQuery(function($){
var count=0;
function handleFileSelect(evt) {
var $fileUpload = $(".imagefet");
count=count+parseInt($fileUpload.get(0).files.length);
if (parseInt($fileUpload.get(0).files.length) > 5 || count>4) {
alert("You can only upload a maximum of 4 files");
count=count-parseInt($fileUpload.get(0).files.length);
evt.preventDefault();
evt.stopPropagation();
return false;
}
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), '"/><span class="remove_img_preview"></span>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
reader.readAsDataURL(f);
}
}
$('.imagefet').change(function(evt){
handleFileSelect(evt);
});
$('#list').on('click', '.remove_img_preview',function () {
$(this).parent('span').remove();
var i = array.indexOf($(this));
if(i != -1) {
array.splice(i, 1);
}
count--;
});
})
</script>
FIXED. See updated code below.
<script type="text/javascript">
jQuery(function($){
$("#clear").click(function(event){
event.preventDefault();
$("#control").replaceWith('<input style="visibility: hidden; position: absolute;" class="imagefet" type="file" name="upload_attachment[]" id="control" multiple="multiple">');
$("div.output-fet").replaceWith('<output id="list"></output>');
});
})
</script>
<!-- File Upload Section BEGIN -->
<label for="control">
<span class="btn">Add Images</span>
</label>
<input style="visibility: hidden; position: absolute;" class="imagefet" type="file" name="upload_attachment[]" id="control" multiple="multiple">
<br><div class="output-fet"><output id="list"></output></div>
Clear
<script type="text/javascript">
jQuery(function($){
var count=0;
function handleFileSelect(evt) {
var $fileUpload = $(".imagefet");
count=count+parseInt($fileUpload.get(0).files.length);
if (parseInt($fileUpload.get(0).files.length) > 5 || count>4) {
alert("You can only upload a maximum of 4 files");
count=count-parseInt($fileUpload.get(0).files.length);
evt.preventDefault();
evt.stopPropagation();
return false;
}
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);
}
}
$('.imagefet').change(function(evt){
handleFileSelect(evt);
});
/*
$('#list').on('click', '.remove_img_preview',function () {
$(this).parent('span').remove();
var i = array.indexOf($(this));
if(i != -1) {
array.splice(i, 1);
}
count--;
}); */
})
</script>
You can't remove files one by one, as the API for FileList has no removing method (probably for security reasons). You can however clear the entire file list, as suggested here: Clearing <input type='file' /> using jQuery

trying to leverage JSZip to open and then parse a specific file in a .zip

Have been trying to use the JSZip library to cycle through files in a .zip, looking for one (here, test.txt) that I want to parse for content.
Have attempted to do a modification of the sample [recommend viewing source on that] that JSZip provides:
<!DOCTYPE HTML>
<html>
<head>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
</head>
<body>
<div class = "container">
<div class = "hero-unit">
<input type="file" class="span7" id="input" name="file" multiple /> <!-- redo this in a bootstrappy way-->
<br>
<output id="output"></output>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="/js/jszip-load.js"></script>
<script src="/js/jszip.js"></script>
<script src="/js/jszip-inflate.js"></script>
<script>
if (window.File && window.FileReader && window.FileList && window.Blob) {
// Great success! All the File APIs are supported.
} else {
alert('The File APIs are not fully supported in this browser.');
}
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
if (f.type !== "application/zip") {
document.getElementById('output').innerHTML = "<p class='text-error'>" + f.name + " isn't a zip file.</div>";
continue;
}
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
var zip = new JSZip(e.target.result)
$.each(zip.files, function (index, zipEntry) {
if (zipEntry.name == "test.txt"){
var text = zipEntry.asText();
var lines = text.split(/[\r\n]+/g); // tolerate both Windows and Unix linebreaks
for(var i = 0; i < lines.length; i++) {
if (lines[i].length > 240){
output.push('<li>' + lines[i] + '<br>');
}
}
document.getElementById('output').innerHTML = '<h2>Paths with more than 240 characters:</h2> <br><ol>' + output.join('') + '</ol>';
else{
alert("file not found!")
}
}
});
}
})(f);
}
}
document.getElementById('input').addEventListener('change', handleFileSelect, false);
</script>
</body>
</html>
For some reason, I'm sure having to do with the way that I am using the closure, it is not actually parsing the .zip files in question. Any ideas what I might be doing wrong here?
I use this code and am able to get all file data. content variable has file content:
function loadSettingsFile(evt) {
var files = evt.target.files;
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
try {
var zip = new JSZip(e.target.result);
$.each(zip.files, function (index, zipEntry) {
var content = zipEntry.asText();
alert(content);
});
} catch(e) {
alert(e)
}
}
})(f);
// read the file !
// readAsArrayBuffer and readAsBinaryString both produce valid content for JSZip.
reader.readAsArrayBuffer(f);
// reader.readAsBinaryString(f);
}
}

Categories

Resources