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.
Related
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.
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>
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/
My Code:
var data = $(input)[0];
var file = data.files[0];
var reader = new FileReader();
reader.onload = function (e) {
value = e.target.result;
try {
top.document.getElementById('formDesignContents').contentWindow.updateFormFromToolbar(CURRENT_ATTRIBUTE, value, opts);
} catch (err) {
alert("error connecting to formDesignContents iframe from the toolbar");
}
}
reader.readAsDataURL(file);
It works in GoogleChrome but not IE. For IE, it does not recognize the attribute files under the input element. The jquery is to dereference a jquery object back into standard html element.
Is there another way to accomplish for IE to work? I can easily do one of those
if(IE){...}else{...}
blocks of code. I just dont see why it doesnt recognize those items.
Has anyone else encountered this?
IE doesn't support FileReader, so I'd expect your script to crash on this line:
var reader = new FileReader();
Unless you are using IE10?
https://developer.mozilla.org/en/DOM/FileReader#Browser_compatibility
Here's my sample code:
var input = document.createElement('input');
input.type = 'file';
document.body.appendChild(input);
input.addEventListener('change', function(){
var file = input.files[0];
var reader = new FileReader();
reader.onload = function(e){
var image = new Image();
image.src = e.target.result;
};
reader.readAsDataURL(file);
});
Load the page, select a large image (I'm using a 2.9MB 4288x3216 image). Refresh the page and select the same image. Result? The tab crashes! (Aw, Snap!)
My guess is that this is a bug with Chrome's implementation of the File API, but I'd love it if someone could confirm that and maybe even offer a workaround. I really want to be able to show a thumbnail of a photo without having to go to the server to generate one (even if it's just for Chrome and FF).
Also, with my sample code above, as soon as you select the photo, the tab starts using about 32MB more of memory. That, I guess, is expected, but what concerns me is that the memory never seems to get freed by the garbage collector. So if I keep selecting more photos, I keep consuming more memory. I don't know if this is related to the crashing issue or not, but it's definitely a concern.
Thanks for any help!
The memory issue could be a result of this bug: http://crbug.com/36142. Essentially, Chrome is caches data: URLs and currently does not release the memory when the img.src is changed. The other issue is that data: URLs yield a 33% overhead to the data you're encoding. That means you're actually setting a ~3.85MB resource on the image, not 2.9MB.
Since you're not manipulating the content (the actual bytes), there's no need to read the file content. One option is to create a blob: url. There's also an explicit revoke method, so you won't run into the same memory caching issues. Something like:
input.addEventListener('change', function(e) {
var file = input.files[0];
window.URL = window.webkitURL || window.URL; // Vendor prefixed in Chrome.
var img = document.createElement('img');
img.onload = function(e) {
window.URL.revokeObjectURL(img.src); // Clean up after yourself.
};
img.src = window.URL.createObjectURL(file);
document.body.appendChild(img);
});