I'm loading a file on my webapp and I use this function I found on a website to read it:
<script>
function readBlob() {
var files = document.getElementById('files').files;
if (!files.length) {
alert('Please select a file!');
return;
}
var file = files[0];
var start = 0;
var stop = file.size - 1;
var reader = new FileReader();
// If we use onloadend, we need to check the readyState.
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
document.getElementById('byte_content').textContent = evt.target.result;
}
};
var blob = file.slice(start, stop + 1);
reader.readAsBinaryString(blob);
}
</script>
The reading works fine but it seems that the "\n\r" is not read and all my lines are stick together.
Is there anything to change in this code to take account of '\n\r' ?
You can solve this problem with CSS only. Demo. MDN.
#byte_content { white-space: pre}
Related
So, what this option should do is let the user upload a file (an image) with <input id="background-image" type=file></input> (this works) but how do I get the background image to stay when a user opens a new tab or closes the current tab.
Here is the JS that sets the background image:
document.getElementById('background-image').addEventListener('change', readURL, true);
function readURL(){
var file = document.getElementById("background-image").files[0];
var reader = new FileReader();
var readFile = reader.readAsDataURL(file);
reader.onloadend = function(){
document.getElementById("main-background-image").style.backgroundImage = "url(" + reader.result + ")";
}
if(file){
reader.readAsDataURL(file);
}else{
}
}
Again this sets the image for the current tab, as long as the user doesn't click away. Is it possible to keep the user's background image for future and other tabs ?
My solution was based on another stackoverflow question: Saving an uploaded image to localStorage (chrome extension)
var input = document.getElementById('getval');
input.onchange = function(evt){
var tgt = evt.target || window.event.srcElement,
files = tgt.files;
if (FileReader && files && files.length) {
var fr = new FileReader();
fr.onload = function () {
localStorage['foo'] = fr.result;
}
fr.readAsDataURL(files[0]);
}
}
after I inserted this bit of code:
window.onload=function(){
var el = document.querySelector('body');
el.style.backgroundImage = 'url(' + localStorage['foo'] + ')';
I get no credit for the code below. It was found online. It works to open a file but I'd need something to display only certain strings withing a file (i.e)
test = 2000
radio 1020
webbrowser - 1000
help needed = 2000
I'd need to modify this to display only, for example, help needed = 2000
<script>
function readBlob(opt_startByte, opt_stopByte) {
var files = document.getElementById('files').files;
if (!files.length) {
alert('Please select a file!');
return;
}
var file = files[0];
var start = parseInt(opt_startByte) || 0;
var stop = parseInt(opt_stopByte) || file.size - 1;
var reader = new FileReader();
// If we use onloadend, we need to check the readyState.
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
document.getElementById('byte_content').textContent = evt.target.result;
document.getElementById('byte_range').textContent =
['Read bytes: ', start + 1, ' - ', stop + 1,
' of ', file.size, ' byte file'].join('');
}
};
var blob = file.slice(start, stop + 1);
reader.readAsBinaryString(blob);
}
document.querySelector('.readBytesButtons').addEventListener('click', function(evt) {
if (evt.target.tagName.toLowerCase() == 'button') {
var startByte = evt.target.getAttribute('data-startbyte');
var endByte = evt.target.getAttribute('data-endbyte');
readBlob(startByte, endByte);
}
}, false);
</script>
First of all, web browsers does not allow you to access local files using javascript for security reasons.
So, if you really want to read the file in javascript, you should consider setting up an environment to execute javascript. You can read it here. Executing javascript without browser.
This is my javascript code.
if (typeof FileReader !== "undefined") {
var filerdr = new FileReader();
filerdr.onload = function(e) {
$('#imgprvw' + fieldno).attr('src', e.target.result);
var imgFileSize = input.files[0].size/1024/1024;
if (imgFileSize <= 1) {
var base64image = e.target.result;
console.log(base64image);
}
else {
var base64image = jic.compress(document.getElementById('imgprvw' + fieldno), 90, ext);
}
var imageBase64 = base64image.replace(/^data:image\/(png|jpeg);base64,/, "");
}
}
im using javascript for IE9.i used filereader API and polyfills also. but i didnt get the solution
I am struck in a problem where I am trying to read a csv file using Browse button by the following HTML tag:
<input type="file" name="filename" id="filename">
<div id="csvimporthint"></div>
and my jquery code to read and process the input file is as below:
<script>
$("#filename").change(function(e) {
var ext = $("input#filename").val().split(".").pop().toLowerCase();
if($.inArray(ext, ["csv"]) == -1) {
alert('Upload CSV');
return false;
}
if (e.target.files != undefined) {
var reader = new FileReader();
var csvLines;
var csvValues;
var i;
reader.onload = function(e) {
csvLines = e.target.result.split("\n");
for(i=1; i<csvLines.length; i++){
csvValues = csvLines[i].split(",");
importedLat = csvValues[0];
importedLon = csvValues[1];
markerFunc(importedLat, importedLon);
addLayer();
}
//$("#csvimporthint").html(importedLat + " " + importedLon);
reader.readAsText(e.target.files.item(0));
};
}
return false;
});
</script>
The problem that I am facing is that my reader.onload is never fired, in result of which I cannot process my file data. Kindly help me find a solution to make this code running.
P.S: To write this above code, I followed this link: http://jsfiddle.net/W8fME/1650/
I have found the answer of this question myself. The problem was in jquery code in the script tag, correct jquery code is as below:
<script>
$("#filename").change(function(e) {
var ext = $("input#filename").val().split(".").pop().toLowerCase();
if($.inArray(ext, ["csv"]) == -1) {
alert('Upload CSV');
return false;
}
if (e.target.files != undefined) {
var reader = new FileReader();
var csvLines;
var csvValues;
var i;
reader.onload = function(e) {
csvLines = e.target.result.split("\n");
for(i=1; i<csvLines.length; i++){
csvValues = csvLines[i].split(",");
importedLat = csvValues[0];
importedLon = csvValues[1];
markerFunc(importedLat, importedLon);
addLayer();
}
};
reader.readAsText(e.target.files.item(0));
}
return false;
});
</script>
So I'm doing a simple multiple image upload script using javascript, but socket.io has to be used in order to get the image into the database. In order to run previews I have been taking event.target.result and putting it as the image src on a div. Is there any way I can store the this in an array for each image so that I can transfer it over the socket, and have it load on the other side? When I try to load it into an array, it's always undefined.
for (var i = 0; file = files[i]; i++) {
name[i] = files[i].name;
// if the file is not an image, continue
if (!file.type.match('image.*')) {
continue;
}
reader = new FileReader();
reader.onload = (function (tFile) {
return function (evt) {
var div = document.createElement('div');
var miniDiv = document.createElement('div');
div.id = "photoDiv";
div.innerHTML = '<img style="width: 120px; height: auto;" src="' + evt.target.result + '" />';
div.className = "photos";
var data = evt.target.result;
picture[i] = data;
document.getElementById('filesInfo').appendChild(div);
document.getElementById('previewDiv').appendChild(document.getElementById('filesInfo'));
};
}(file));
reader.readAsDataURL(file);
}
uploadFiles();
}
Don't make functions within a loop like that, it can lead to unexpected things.
I would suggest using JSHint, it's very helpful.
You made two mistakes:
1) You should pass i variable to your closure together with file.
2) The most important: reader.onload is a function that will be called not immediately, but in some delay, and as a result it will be called after uploadFiles() call. That's why you get an empty picture.
Try to rewrite your code as follows:
var done = 0;
var picture = [];
for (var i = 0; file = files[i]; i++) {
name[i] = files[i].name;
// if the file is not an image, continue
if (!file.type.match('image.*')) {
if (++done === files.length) {
uploadFiles();
}
continue;
}
reader = new FileReader();
reader.onload = (function (tFile, index) {
return function (evt) {
//[...]
picture[index] = data;
//[...]
if (++done === files.length) {
//the last image has been loaded
uploadFiles();
}
};
}(file, i));
reader.readAsDataURL(file);
}