iOS' browser only allows JavaScript FileReader to read images. Renaming images to .txt will make them fail the check, so I guess some validation exists.
Is there a way to bypass it?
$("#fileinput").change(function(evt){
var r = new FileReader();
r.onload = function(evt){ //file loaded successfuly
contents = evt.target.result;
...
}
r.readAsText(f);
});
Related
I want the user of my website to be able to upload a potentially large video file to it using HTML‘s file input. The video should than be processed and played locally in the user‘s browser.
let fileInput = document.createElement("INPUT");
fileInput.setAttribute("type", "file");
fileInput.onChange = onFileSelected;
To read the video file uploaded by the user, I wanted to use a File Reader like this:
function onFileSelected(e) {
// The file uploaded by the user:
let file = e.target.files[0];
// Create a file reader:
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e) {
video.src = e.target.result;
}
}
However, when I uploaded really large video files (≈300 MB), e.target.result was not a URI to the video file, like I expected, but an empty string.
How can I read very large video files using File Reader in JavaScript?
The FileReader class in JavaScript contains multiple methods to read files:
readAsText(): This reads a file and returns its content as text. Suitable for small text files.
readAsBinaryString(): This reads a file and returns its content as a binary string. Suitable for small files of any type.
readAsDataURL(): This reads a file and returns a Data URL referencing it. This is inefficient for large files as the file is loaded into memory as a whole before being processed.
readAsArrayBuffer(): This reads a file and returns an ArrayBuffer containing the input file 'chopped up in smaller pieces'. This works for very large files, too.
In the question, the readAsDataURL() method is used as it is usually most convenient. However, for very large video files (and very large files in general) it does not work for the reason described above leading to an empty result. Instead, you should use readAsArrayBuffer():
let reader = new FileReader();
reader.readAsArrayBuffer(file);
Now, the file reader returns an ArrayBuffer after loading the file. In order to be able to show the video in HTML, we have to convert this buffer to a blob, that can then give us a URL to the video file:
reader.onload = function(e) {
// The file reader gives us an ArrayBuffer:
let buffer = e.target.result;
// We have to convert the buffer to a blob:
let videoBlob = new Blob([new Uint8Array(buffer)], { type: 'video/mp4' });
// The blob gives us a URL to the video file:
let url = window.URL.createObjectURL(videoBlob);
video.src = url;
}
I need to get the name, format and content of a browsed file only, multiple files not required. Even I cant use any HTML5 API/jQuery. Could you please guide me, using only pure JavaScript how do I solve this.
Here is the fiddle:
[https://jsfiddle.net/summtz8m/][1]
After getting all I need to click ImportASN1 button to POST data in REST service.
Here is my HTML
<button class="ebBtn" id="importButt" name="importButt"><span>Import ASN1</span></button><input type="file" id="myfile" name="myfile"><p id="contents"></p>
Here is my JS
var file = document.getElemtById("myfile").files[0];
console.log(file);
if (file) {
// create reader
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(e) {
// browser completed reading file - display it
console.log(e.target.result);
};
}
Your current code runs on page load. But at that time the file input is not filled out yet! Instead, listen to the click event on the button, or the change event on the file input.
In addition, there is a typo: document.getElemtById should be document.getElementById. Use the developer console in your browser (F12 → Console in many browsers) to find these errors.
The file name will then be present in the file.name property.
<script>
document.getElementById("myfile").addEventListener('change', function(ev) {
var file = ev.target.files[0];
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(e) {
console.log(file.name, e.target.result);
};
});
</script>
I've got a FileReader that lets the user upload a file (image) to my site.
Here's the code that does the reading:
$("input[type='file']").change(function(e) {
var buttonClicked = $(this);
for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {
var file = e.originalEvent.srcElement.files[i];
var img = document.createElement("img");
var reader = new FileReader();
reader.onloadend = function() {
img.src = reader.result;
console.log(reader.result);
}
reader.readAsDataURL(file);
}
});
All is good and well, until I tried to print out my result. I used this file for example:
When I console.log() the result, it spits out over 95000 characters.
This image in particular is around the same size as the images I will be accepting into my site.
I was hoping to store these images in a database as well, and so I'm wondering how this is going to be possible with image sources that are so extremely long. Is there a way to shorten this or get the image path a different way?
I'm moreso curious as to why they're so long, but if someone has a tip to store these (100s per user, 500+ users) that'd be nice as well!
Thanks-
Store the Files as ... Files.
There are very little use cases where you need the toDataURL() method of the FileReader, so every time you use it, you should ask yourself why you need it.
In your case :
To display the image in the page. Well don't use a FileReader for this, instead create a direct pointer to the file in the form of an url, available only to this session. This can be achieved with the URL.createObjectURL(File_orBlob) method.
To store this image on your server. Don't store a ~37% bigger base64 version, send and store directly the file as a file (multipart). This can be achieved easily with the FormData API.
inp.onchange = function(){
var file = this.files[0];
if(file.type.indexOf('image/') !== 0){
console.warn('not an image');
}
var img = new Image();
img.src = URL.createObjectURL(file);
// this is not needed in this case but still a good habit
img.onload = function(){
URL.revokeObjectURL(this.src);
};
document.body.appendChild(img);
}
// not active but to give you da codez
function sendToServer(){
var file = inp.files[0];
var form = new FormData();
// here 'image' is the parameter name where you'll retrieve the file from in the request
form.append('image', file);
form.append('otherInfo', 'some other infos');
var xhr = new XMLHttpRequest();
xhr.open('post', 'yourServer/uploadPage')
xhr.onload = function(){
console.log('saved');
};
xhr.send(form);
}
<input type="file" id="inp">
And if you need PHP code to retrieve the File form this request :
if ( isset( $_FILES["image"] ) ){
$dir = 'some/dir/';
$blob = file_get_contents($_FILES["image"]['tmp_name']);
file_put_contents($dir.$_FILES["image"]["name"], $blob);
}
You're going to want to upload the files to a server of some sort (a backend that is serving up your javascript), and then from there you'll want to
Validate the file
Store the file on a physical server (or the cloud) somewhere
Add an entry in a database that relates the file path or ID of that upload to the user who just uploaded it (so you can retrieve it later if needed)
So basically, you don't store the image in your database, you store it on a file share/cloud host somewhere, and instead you only store what is needed to download/retrieve the image later.
Is it possible to create an HTML image, if I have only a path to a local file? I tried to use a filereader, but the mere path does not work. how can I solve the issue?
JS
var reader = new FileReader();
reader.onload = {
$('#myImg').attr('src', e.target.result);
};
reader.readAsDataURL("file:///C:/Users/me/AppData/Local/Temp/msohtmlclip1/01/clip_image002.jpg ");
This is a simple tool I have made for reading files in JavaScript:
Fiddle
The JavaScript code is:
var reader = new FileReader();
reader.onerror = function(ev) {
$('#output').html('=== Error reading file ===');
}
reader.onload = function(ev) {
$('#output').html(ev.target.result);
};
reader.readAsDataURL(e.target.files[0]);
When you select an image file it will present you with a base64 dataURI of the image.
I recommend not trying to select a file that's not an image, I don't know what'll happen.
something like this?
var x=document.createElement("img");
x.src="C:\data\images\test.jpg";
x.style.height="50px";
document.getElementById('whereimgoing').appendChild(x);
Also I should add that if this is on a website then it will depend highly on browser security
var reader = new FileReader();
reader.onload = function(e) {
$('#myImg').attr('src', reader.result);
};
reader.readAsDataURL("file:///C:/Your/path/msohtmlclip1/01/clip_image002.jpg");
Should be fine, if access to local files is granted (check your browser settings or try if it works when deployed on a server (either localhost or www.yourserver.com).. Local files can always cause some troubles as browser behave differently. Also try to not use the temp folder.
I am trying to allow a user to upload an image onto a canvas of size 200MB, but when I choose that image, I get the aw snap error from google chrome. I thought there were no limitations on the FileReader API in terms of image size.
If I set the image.src to that large image within the code, it loads in seconds. But for some reason it keeps crashing when the user tries to load it. If anyone can help with this that would be great. Or if there are any suggestions on how to load a large image to a canvas other than this that would also be great.
Thanks
function handleImage(e){
//clearAnnotations();
//annoRedraw();
//redraw();
var reader = new FileReader();
reader.onload = function(event){
image.src = event.target.result;
redraw();
}
imageName = e.target.files[0].name;
reader.readAsDataURL(e.target.files[0]);
imageLoadedCheck();
}
and handleImage function is called by this listener
imageLoader.addEventListener('change', handleImage, false);