JS - file onload() doesn't work with android browser - javascript

I have a application similar to the example http://jsfiddle.net/jonathansampson/K3A9r/
But if I use this concept for file upload on a iPad/android it does not work. The image is not loaded into the browser wether with onload() nor with onloadend()
html:
<input type="file" name="myFileSelect" />
js:
// Bind to the change event of our file input
$("input[name='myFileSelect']").on("change", function(){
// Get a reference to the fileList
var files = !!this.files ? this.files : [];
// If no files were selected, or no FileReader support, return
if ( !files.length || !window.FileReader ) return;
// Only proceed if the selected file is an image
if ( /^image/.test( files[0].type ) ) {
// Create a new instance of the FileReader
var reader = new FileReader();
// Read the local file as a DataURL
reader.readAsDataURL( files[0] );
// When loaded, set image data as background of page
reader.onloadend = function(){
$("html").css("background-image", "url(" + this.result + ")");
}
}
});

I don't believe the onloadend event is well supported in android or ios. IE 10 does not support this event on FileReader as well, I think. Perhaps you should rely on the onload event instead.

File.API works from android browser 3.0+
or user firefox on the android device
http://mobilehtml5.org/

Related

how do i get any images in binary code using js?

I want to make a multiple images upload system with prograss bar. I want to do with simaple code(using jquery or js). I want when user has upload his images on browser and i want to show on browser that images and with upload button he starts uploading image via ajax in his folder.
So questions
1.) Is it possible to show uploaded image (without any complicated code) ?
2.) Do i get a variable or array where uploaded images are stored as base64 code (data:/img:dfd5d/d54fs..... something like this) or encoded?
3.) How do i add progressBar ?
I didn't write any code yet because i dont know how to start. I am new in computer science.
But i find this code on this site
function previewFile() {
var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
}
This is easy code and i understand but one thing is not clear what does mean this line var reader = new FileReader(); why use new and what is it ?
Ty in advance and please dont explain complicate and i am not very good in english. So please try to explain in poor words if possible..
Assuming that you have this field
<input type="file" onchange="showImage(this)"/>
you can create a script to take the binary data and show it
function showImage(input){
var reader = new FileReader();
// validating...
var fileType = input.files[0].type;
var filesize = input.files[0].size;
// filetype (this will validate mimetype, only png, jpeg, jpg allowed)
var fileTypes = ["image/png", "image/jpeg", "image/gif"];
if (fileTypes.indexOf(fileType) < 0){
// return error, invalid mimetype
return false;
}
// file cannot be more than 500kb
if (filesize > 5000000) {
// return error, image too big
return false;
}
reader.onload = function (e) {
// e will contain the image info
jQuery('#myimagetopreview').attr('src', e.target.result)
}
reader.readAsDataURL(input.files[0]);
}
This should work, if you have problem tell me
edit: FileReader is not supported by all the browsers, check the documentation for more https://developer.mozilla.org/en/docs/Web/API/FileReader
The FileReader in JS has Status "Working Draft" and isn't part of the official JS API. I think you have to wait until the Browsers support this ne API or you have to activate experimental JS API in the Browser.

Using FileReader to read cloud images in Android browser

I have the following javascript which provides an image upload button and displays the image:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#target').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
The full jsfiddle is here:
http://jsfiddle.net/6NXwv/
This code works on every mobile browser I've tried except for the stock Android browser. Specifically images only fail to load if they are stored remotely but appear in the gallery (for example synced facebook or picasa images). Now I know FileReader is only for LOCAL files however chrome browser, opera, and firefox mobile have no issues.
I checked the FileReader error code, it appears that gallery images from facebook/picasa return NOT_FOUND_ERR:
https://developer.mozilla.org/en-US/docs/Web/API/FileError
If this is a case of FileReader not able to read remote files why does it work in all other mobile browsers?
I can't find anyone else having this exact issue, everything I google keeps returning this result:
Issue with stock Browser picking photos from Gallery
However the mime-type appears to be detected correctly. The mime-type shows up and the filename shows the correct name but the actual data isn't there (also File.size reports '0'). I've been able to recreate this on the stock android browser on 4.4 and 4.3. Haven't tested older versions.
In short when selecting photos via the gallery, local files and new images taken with the camera load correctly but remote facebook/picasa files (on 4.4 at least they have little fb/picasa icons on their thumbnails in the gallery) do not load. Only occurs in stock browser.
The error you face have 2 explanation.
First explanation is that the files "Images" that you tried to read with HTML5 API FileReader are looked or on use by other applications "like Facebook or Picasa" and in this case you can do nothing about it from js unless you have physical access to the hardware "Phone".
second explanation which is more likely is some browsers can't fire the event onload of FileReader because they are not fully supporting this HTML5 API. you can read more about this in caniuse website. And that can be solve by changing the event onload to onloadend.
here is how your code should be :
var reader = new FileReader();
reader.onloadend = function () {
console.log(reader.result);
};
reader.readAsDataURL(file);
here is example: jsfiddle
here is Demo: Demo FileReader Html5
<input id="fileinput" name="arquivo[]" type="file" multiple="multiple" onchange="FileDetails()"/>
<var id="file_List"></var>
<button type="button" onclick="Click()">Click Me!</button>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
<script>
// simple routine to put content of file input files into memory
G_Array = [];
G_Cont_Upload = 0;
function Click()
{
var a = 1; // this is only to check the content of global variable as google chrome does not stop inside f_ReadFile
}
function FileDetails()
{
var file_arr = [];
if (typeof (FileReader) != "undefined")
{
var files = $('#fileinput')[0].files;
var reader = [];
for (var i = 0; i < files.length; i++)
{
var FileDet = files[i];
var name = FileDet.name;
var Size = FileDet.size;
var Obj = {Name: FileDet.name, SizeInicial : FileDet.size};
G_Array.push(Obj);
reader[i] = new FileReader();
function f_ReadFile(e)
{
var content = e.target.result;
G_Array[G_Cont_Upload].SizeAtual = content.length;
G_Array[G_Cont_Upload].Content = content; // content base 64
G_Cont_Upload++;
}
reader[i].onload = f_ReadFile;
reader[i].readAsDataURL(FileDet);
}
}
else
{
alert("This browser does not support HTML5 FileReader.");
}
}
</script>
</body>

Cordova 3.4 FileReader not working (no onloadend)

I am updating an app from phonegap 2.* to cordova 3.4
Things are running smooth now, only the file download is not working.
I need to download a file from the internet (host edited) and store it as an JSON file, to have the contents processed later on.
The download is working fine, the file will be shown in the filesystem, but the FileReader does not fire the onloadend event.
I have tried a few things like onprogress or onerror events, also file.toURI and FileReader.readAsDataURL - nothing worked. Anybody any ideas?
Notes:
app.log can be seen as an alias for console.log
print_r is defined in another file, working fine
The downloaded file is just a few kB, shouldn't be a performance issue
Running on iOS hardware
Full code (extracted and shortened):
var fileTransfer = new FileTransfer();
var loadingStatus = 0;
fileTransfer.onprogress = function (progressEvent) {
// if we have the complete length we can calculate the percentage, otherwise just count up
if (progressEvent.lengthComputable) {
loadingStatus = Math.floor(progressEvent.loaded / progressEvent.total * 100);
} else {
loadingStatus++;
}
app.log('Transfer Progress: ' + loadingStatus);
};
fileTransfer.download(
encodeURI('http://www.example.com/export'),
'cdvfile://localhost/persistent/import.json',
function (file) {
var FileReader = new FileReader();
FileReader.onloadend = function (evt) {
app.log('Filereader onloadend');
app.log(evt);
};
FileReader.readAsText(file);
},
function (error) {
// FileTransfer failed
app.log("FileTransfer Error: " + print_r(error));
}
);
The File API has been updated. See this post: https://groups.google.com/forum/#!topic/phonegap/GKoTOSqD2kc
file.file(function(e) {
console.log("called the file func on the file ob");
var reader = new FileReader();
reader.onloadend = function(evt) {
app.log('onloadend');
app.log(evt.target.result);
};
reader.readAsText(e);
});
Cant verify this at the moment but since 3.0, Cordova implements device-level APIs as plugins. Use the CLI's plugin command, described in The Command-line Interface, to add or remove this feature for a project:
$ cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-file.git
$ cordova plugin rm org.apache.cordova.core.file
Did you add the plugin to your project?

how to get file input in IE on change

I need to get a file on load to input.
This code works in chrome, opera and firefox but not with IE:
$("input:file").change(function ()
{
// Get a reference to the fileList
var files = !!this.files ? this.files : [];
// If no files were selected, or no FileReader support, return
if ( !files.length || !window.FileReader ) return;
// Only proceed if the selected file is an text
if ( /^text/.test( files[0].type ) )
{
var reader = new FileReader();
reader.readAsText( files[0] );
reader.onloadend = function()
{
restoreCSS(this.result);
}
}
}
In IE !!this.files return false. Thank's for advance.
Which version of IE are you using? FileReader isn't supported in IE until version 10.
As #apsillers commented, there's another question asking about how to imitate FileReader support in browsers that don't support it. I believe they all require some sort of plugin (Flash/Silverlight), as before the FileReader API, JavaScript did not have any access to the file system.

file reader is not working in chrome and IE

I upload an image file from my PC and then read it as dataurl. Then pass it to img element to preview it. It is working fine in firefox. But in chrome and IE, it doesn't get the src from the file reader.
Here is what i'm doing,
var image = document.createElement("img");
var thumbnail = document.getElementById("thumbnail");
image.file = file;
thumbnail.appendChild(image);
function handlefilereader(evt){
image.src = evt.target.result;
}
var reader = new FileReader()
reader.onload = handlefilereader;
reader.readAsDataURL(file);
image.id = count;
count++;
image.draggable = true;
image.ondragstart = dragIt;
alert(image.src);
Filereader may not be supported in your browser versions. See this compatibility chart.
http://caniuse.com/filereader
Also, event.target is not fully browser compatible. Consider
var target = evt.target || evt.srcElement;
image.src = target.result;
Like people here mentioned, File API is not supported in IE. But no one mentioned a possible solution. Here is one --> FileReader + flash
So you can still use FileAPI in IE.

Categories

Resources