Passing image data to another page - javascript

I'm trying to access a camera and a photo album on a mobile device and get the chosen image. I did that with the code below. My problem is, it generates image data, and I have to transfer that to another page, but because of the size of the generated string, I can't use URL parameters. It shows me the error: [404] Request-URI Too long. How can I pass the information to the other page?
Here is the code: http://jsfiddle.net/8u426/
The JS:
<script>
oFReader = new FileReader();
oFReader.onload = function (oFREvent) {
document.getElementById("fotoImg").src = oFREvent.target.result;
document.getElementById("fotoImg").style.visibility = "visible";
var screenHeight = screen.availHeight;
screenHeight = screenHeight - 220;
document.getElementById("fotoImg").style.height = screenHeight;
document.getElementById("stringImg").innerText = "Data Image: " + oFREvent.target.result;
};
$(function() {
$("input:file").change(function (){
var input = document.querySelector('input[type=file]');
var oFile = input.files[0];
oFReader.readAsDataURL(oFile);
});
});
</script>
Update:
The problem is: if I try to open a new page passing the Data Image string as a parameter in the URL (with "?"). The new page will show the 404 error that I mentioned, because the string is too long.

Try changing your form to
<form id="form1" method="POST" action="[Page2 URL]">
<input id="filePic" type="file" name="image" accept="image/*" capture />
</form>
where [Page2 URL] is the URL for page to receive the image uploaded.
And JavaScript to
oFReader = new FileReader();
oFReader.onload = function (oFREvent) {
var screenHeight = screen.availHeight;
screenHeight = screenHeight - 220;
var img = $('#fotoImg');
img.attr('src', oFREvent.target.result);
img.css( { height : screenHeight, visibility: 'visible' });
$("#stringImg").text( "Data Image: " + oFREvent.target.result);
$('#form1').submit();
};
$(function() {
$("input:file").change(function (){
var oFile = this.files[0];
oFReader.readAsDataURL(oFile);
});
});

I couldn't make work with php (considering that I didn't want to work with php) and html forms (methods get and post)... So I used the jQuery library called "jQuery Storage".
It was easy, on the page that I select the image you shoud use:
$.sessionStorage([key],[value]);
So, was like that:
$.sessionStorage('chosenImg', document.getElementById("photoImg").src);
And in the new page, to get the value, just add in the code:
$.sessionStorage('chosenImg');
Of course, I had to download de .js library from the website and add the line below on both html pages:
<script src="jquery.storage.js"></script>
The only inconvenient it is a little heavy for mobile, but was the only way I found...
That is it! Thanks everyone!
dataimage base64 data image

Related

Uncaught TypeError: Failed to execute 'readAsText' on 'FileReader': parameter 1 is not of type 'Blob'

I wrote a function to read HTML from a file and set the innerHTML of a certain div to equal the HTML inside the file, as a kind of save/load system. This used to work fine, however after a browser update I am getting the error seen in the title.
HTML:
<div id="target">
<button onclick="saveDiv()">Save</button>
<button onclick="loadDiv()">Load</button>
<input id="file" type="file" style="hidden">
<input>
</div>
JS:
const div = document.getElementById('target')
function saveDiv() {
var divContent = div.innerHTML.toString();
var ran = (Math.random() + 1).toString(36).substr(2, 8)
var fileName = `${ran}.txt`;
download(fileName, divContent);
}
function download(name, content) {
var e = document.createElement('a');
e.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(content));
e.setAttribute('download', name);
e.style.display = 'none';
document.body.appendChild(e);
e.click();
document.body.removeChild(e);
}
function loadActors() {
document.getElementById('file').click();
var file = document.getElementById('file').files[0];
var r = new FileReader();
r.onload = (function(reader) {
return function() {
var contents = reader.result;
div.innerHTML = contents;
}
})(r);
r.readAsText(file);
}
I think what may be happening is that the FileReader is trying to read the file before the user has selected it, but I'm not exactly sure. Anyone know what may be happening here?
Edit: Seems that if I select the file after the error then click the load button again it runs fine. How would I make it only run after the user has selected the file?

I want to extract a string from a text file and output it as a text file again

I want to extract a string from a text file, convert it to a word scrambler (I figured out that part) and output it in another text file.
I found some code to input a text file and extract the text:
<html>
<h4>Select un file con .txt extension</h4>
<input type="file" id="myFile" accept=".txt" />
<br /><br />
<div id="output"></div>
<script>
var input = document.getElementById("myFile");
var output = document.getElementById("output");
input.addEventListener("change", function () {
if (this.files && this.files[0]) {
var myFile = this.files[0];
var reader = new FileReader();
reader.addEventListener("load", function (e) {
output.textContent = e.target.result;
});
reader.readAsText(myFile);
}
});
</script>
</html>
Input text and extract a text file
<html>
<div>
<input type="text" id="txt" placeholder="Write Here" />
</div>
<div>
<input type="button"id="bt"value="Save in a File"onclick="saveFile()"/>
</div>
<script>
let saveFile = () => {
const testo = document.getElementById("txt");
let data = testo.value;
const textToBLOB = new Blob([data], { type: "text/plain" });
const sFileName = "Testo.txt";
let newLink = document.createElement("a");
newLink.download = sFileName;
newLink.href = window.URL.createObjectURL(textToBLOB);
newLink.style.display = "none";
document.body.appendChild(newLink);
newLink.click();
};
</script>
</html>
But I don't know how to output a string in the first code or how to connect it to the second code. Could someone please show me how to do it or explain how these codes work so that I could try to do it myself in JavaScript?
I will comment each line of JavaScript, that should help you understand.
<script>
/*This creates a global variable with the HTML element input in it. */
var input = document.getElementById("myFile");
/*This creates a global variable with the HTML element div with id output in it. */
var output = document.getElementById("output");
/* this 2 lines are used to set the source and the destination.
The first will get where you put your file, in this case it's the input element.
The second will get the div which content will be replaced by the content of your txt file. */
/* Here we tell to our input element to do something special when his value changes.
A change will occur for example when a user will chose a file.*/
input.addEventListener("change", function () {
/* First thing we do is checking if this.files exists and this.files[0] aswell.
they might not exist if the change is going from a file (hello.txt) to no file at all */
if (this.files && this.files[0]) {
/* Since we can chose more than one file by shift clicking multiple files, here we ensure that we only take the first one set. */
var myFile = this.files[0];
/* FileReader is the Object in the JavaScript standard that has the capabilities to read and get informations about files (content, size, creation date, etc) */
var reader = new FileReader();
/* Here we give the instruction for the FileReader we created, we tell it that when it loads, it should do some stuff. The load event is fired when the FileReader reads a file. In our case this hasn't happened yet, but as soon as it will this function will fire. */
reader.addEventListener("load", function (e) {
/* What we do here is take the result of the fileReader and put it inside our output div to display it to the users. This is where you could do your scrambling and maybe save the result in a variable ? */
output.textContent = e.target.result;
});
/* This is where we tell the FileReader to open and get the content of the file. This will fire the load event and get the function above to execute its code. */
reader.readAsText(myFile);
}
});
</script>
With this I hope you'll be able to understand the first part of this code. Try putting the second part of your code instead of output.textContent and replacing data with e.target.result, that should do what you wish, but I'll let you figure it out by yourself first, comment on this answer if you need further help !
Here's a codepen with working and commented code:
https://codepen.io/MattDirty/pen/eYZVWyK

Load UTF-8 text or html file and add it to dom with JavaScript

I want to read content of a txt or HTML file (some HTML element saved in before) and add them to current page. (like importing template in sliders). I found this code That's work correctly:
var input = document.getElementById("myFile");
var output;
document.getElementById('myFile').addEventListener("change", function() {
if (this.files && this.files[0]) {
var myFile = this.files[0];
var reader = new FileReader();
reader.addEventListener('load', function(e) {
document.getElementById("aDivToShowResult").innerHTML = e.target.result;
});
reader.readAsText(myFile);
}
});
<input type="file" id="myFile">
<div id="aDivToShowResult">
</div>
But my content contain UTF-8 characters!!
(my page totally has UTF-8 charset but Note that the page does not reload when adding code!!
also the txt file saved in UTF-8)
how can I read file and its content(and add to DOM) by UTF-8 charset by JS??
If this is not possible, is there a library or other code to suggest?
You did great, you just have one tiny mistake: if you do innerHTML it will expect to receive some HTML. But you want to add text, right? Then you have to use the method: element.innerText = 'your text'
It's different because the later generates a text node, while the first will try to parse some HTML and add it to the DOM as Element Nodes.
Here's some reference:
innerHTML
innerText
var input = document.getElementById("myFile");
var output;
document.getElementById('myFile').addEventListener("change", function() {
if (this.files && this.files[0]) {
var myFile = this.files[0];
var reader = new FileReader();
reader.addEventListener('load', function(e) {
document.getElementById("aDivToShowResult").innerText = e.target.result;
});
reader.readAsText(myFile);
}
});
<input type="file" id="myFile">
<div id="aDivToShowResult"></div>

control height and width client side with javascript

this is my form
<form action="#" enctype="multipart/form-data" method="post" name="..." id="formPhoto" class="fmp">
<input type="file" name="pho" id="photo" class="inph" accept="image/*">
<button type="submit" id="subFormPhoto" class="spp">press here</button>
</form>
and this is my code JS
<script type="text/javascript">
var inputPhoto= document.getElementById('photo');
inputPhoto.onchange=function(){var photo= this.value; photo.onload=function(){alert(this.width+' '+this.height);};};
</script>
my problem is that not visualize alert(this.width+' '+this.height);.
as if not load photo
this.value gives the file name as a string, so your photo.onload function isn't really looking at the photo but just some string. If you alert or console.log photo you will see what I mean.
You may wish to consider the File API, it will work with modern browsers as from HTML 5.
Here's a working example of your code:
var inputPhoto = document.getElementById('photo');
inputPhoto.onchange = function() {
var file = this.files[0];
var reader = new FileReader();
var photo = new Image();
reader.readAsDataURL(file);
reader.onload = function(_file) {
photo.src = _file.target.result;
photo.onload = function() {
alert(this.width + ' ' + this.height);
};
};
};
I have tried to create what I understood from your question
http://jsfiddle.net/qo8ovmhn/
<input type="file" name="pho" id="photo" class="inph" onchange="myFunction()">
<img id="view" src=""></img>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("photo");
var file = x.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(_file) {
var img = document.getElementById("view");
img.setAttribute("src",_file.target.result);
var height = img.offsetHeight;
var width = img.offsetWidth;
alert(width + " X " + height);
};
}
</script>
see if this is what you were looking for.
The change event of the input is called on choosing an image. The image bytes are read and put in an image tag. Then the dimensions of the image are fetched from the height and width of the image component.
You can hide the image by adding a css style of visibility:hidden or opacity:0
Do not give display:none as this will result in height and width of 0px
Finally the dimensions are shown in an alert.

AngularJS + Firebase Upload profile image

I have a JavaScript image uploader which will upload an image and give me the image src. I need to save this value in my FireBase DB for the current user being created.
I tried outputting the img.src to a hidden input but that didn't seem to work. Like so:
$('.userImageValue').val(img.src);
<input class="userImageValue" ng-model="data.userImage" style="display: none;">
I just figured out if I change the value once it is added to the invisible input it works. So how can I best make the input "register" after the src value is inserted?
Here is the controller where a new user is created.
$scope.list = $firebaseArray(new Firebase("https://my-db.firebaseio.com/users"));
// Create user button
$scope.add_new_user = function() {
console.log($scope.data);
$scope.list.$add($scope.data);
$scope.data = {};
}
This is an input on the page which currently works with the above code and saves a new field for the current user being created.
<input id="firstname" type="text" ng-model="data.firstname" class="form-control" placeholder="First name">
This is the part I am stuck on I need to save the value of img.src from the code below as a new field in the FireBase DB for the user currently being created.
var userImageUploader = document.getElementById('userImageUploader');
userImageUploader.addEventListener('change', function(e) {
var file = userImageUploader.files[0];
var imageType = /image.*/;
if (file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function(e) {
var img = new Image();
img.src = reader.result;
}
reader.readAsDataURL(file);
}
});
I hope that makes sense and thank you in advanced!
You may want to consider using Parse for the image portion.
1) it also has a free tier but with much larger storage than the firebase free tier, which will quickly be exhausted by images.
2) it has better tools for images imo.

Categories