I cannot load files users select in a HTML input because the loader expects a URL linux style URL I guess. I have tried feeding it a blob as a URL object, feeding the raw data to the FBX loader, and most recently feeding the mozilla path to it on my system, but nothing works. How can this be achieved without physically uploading the file to the site and passing an actual URL?
This is my latest attempt:
$(document).ready(function() {
$('#file').change(function () {
if ( this.value == '' ) {
console.log( "No valid file selected." );
}
var filePath = this.files[0].mozFullPath,
loader = new THREE.FBXLoader();
loader.load( filePath, function( object ) {
object.traverse( function( c ) {
if ( c instanceof THREE.Camera ) {
// Debug log
console.log( c );
}
} );
});
});
});
Try a combination of a file input HTML element and the FileReader API. Something like:
const fileInput = document.querySelector("#file-input");
fileInput.addEventListener("change", function(event) {
const reader = new FileReader();
reader.addEventListener("load", function(event) {
const contents = event.target.result;
const loader = new FBXLoader();
const object = loader.parse(contents);
scene.add(object);
});
reader.readAsArrayBuffer(this.files[0]);
});
Related
I am trying to achieve to create a File object from a URL. I tried hard but didn't find a solution to resolve this issue. Could someone please help me how to resolve this issue?
code
let blobImages =
nextProps &&
nextProps.input &&
nextProps.input.value &&
nextProps.input.value.map((item) => {
let file = new File([item.url], { type: 'image/png' })
return file
})
I am using this code but this code doesn't work it give me break image result.
Try the following approach:
HTML:
<img id="myImage"/>
JAVASCRIPT:
// Accept an external ArrayBuffer from a service (cloud,external server etc.)
var request = new XMLHttpRequest();
// For testing lets say this is your URL
request.open( "GET", "https://upload.wikimedia.org/wikipedia/commons/thumb/0/02/Circle-icons-computer.svg/512px-Circle-icons-computer.svg.png", true );
// Identify that your response has declared as arraybuffer
request.responseType = "arraybuffer";
// If you are using DOM object, definitelly you will use blob to create your file object
request.onload = function( e ) {
var arrayBufferView = new Uint8Array( this.response );
var blob = new Blob( [ arrayBufferView ], { type: "image/jpeg" } );
// Parse and create your image from url
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL( blob );
// Access your div element, where your photo will be presented.
// Here instead you can alter the code to download the image as file...
var img = document.querySelector( "#myImage" );
img.src = imageUrl;
};
request.send();
I'm trying to get the height of the image from base64. Here's my code,
let reader = new FileReader()
reader.readAsDataURL(file);
reader.onloadend = function() {
let img = document.createElement('img');
img.src = reader.result; //data:image/png;base64,...
console.log(img.height);
}
and looking on log it return 0.
How to get the height of the image in that way?
Full code
function handleDrop(e) {
var dt = e.dataTransfer
var files = dt.files
handleFiles(files)
}
function handleFiles(files) {
files = [...files]
files.forEach(previewFile)
}
function previewFile(file) {
let reader = new FileReader()
reader.readAsDataURL(file);
reader.onload = function() {
let img = document.createElement('img');
let div = document.createElement('div');
img.src = reader.result;
div.appendChild(img);
document.getElementById('gallery').appendChild(div);
}
}
dropArea.addEventListener('drop', handleDrop, false)
Where-possible you should use createObjectURL instead of using data:-URIs in scripts because a data:-URI requires serializing the entire object into memory as a string with 1/3rd extra memory usage (so if you have a 1MB-sized image, you now need an additional 1.33MB just for the data: URI string, whereas an object URL is usually just a short GUID).
Creating data URIs is also synchronous and blocks the UI thread - you can easily freeze a Chrome tab by creating a data: URI from a large image or video.
Whereas createObjectURL is very, very cheap - the only catch is you need to watch the lifetime of the URL and make sure you use revokeObjectURL.
Change your code to this.
Note that FileReader is not needed at all.
async function printImageDimensions( file ) {
if( !file ) return;
if( !( file instanceof File ) ) return;
//
const img = document.createElement( 'img' );
const objUrl = URL.createObjectURL( file );
try {
const dim = await loadImageAsync( img, objUrl );
console.log( "Width: %d, Height: %d", dim.w, dim.h );
}
finally {
URL.revokeObjectURL( objUrl );
}
}
function loadImageAsync( img, url ) {
return new Promise( ( resolve, reject ) => {
function onLoad() {
const ret = { w: img.naturalWidth, h: img.naturalHeight };
resolve( ret );
}
function onError() {
reject( "Load failed." );
}
img.addEventListener( 'load', onLoad );
img.addEventListener( 'error', onError );
img.src = url;
} );
}
Hello! I'am trying to make it work a function called loadDocument, who need a url of the loaded files from the user local computer to work. I'm writing an API to load document from local user computer, and show it on a web reader.
This is my upload button :
<input type="file" id="input" onchange="module.onLoadSelection();" alt="Browse" name="upload"/>
This is my function without fileReader :
var onLoadSelection = function () {
var select = document.getElementById('input');
if (select && select.value) {
var id= '';
var url = select.files.item(0).name;
module.loadDocument(url,id);
}
};
This is my function with fileReader :
var loadTest = function (input) {
var file = document.querySelector('input[type=file]').files[0];
console.log("file loaded! ->", file); // i can read the obj of my file
var reader = new FileReader();
var id = ''; // don't need rightnow
var url = reader.readAsDataURL(file);
console.log("url :", url); // show me undefined....
module.loadDocument(url,id);
}
What i am trying is to get the url of the loaded file from user computer to get my function loadDocument working. She need a url parameter to work.
loadDocument is an API function, i assume i can't get the filepath of my user due to security reason.
What do i need to change/update on my loadDocument(); function to work?
Edit : In fact, nothing to change. The correct way to read my file was :
<input type="file" id="input" onchange="module.onLoadSelection(this.files);" alt="Browse" name="upload"/>
var onLoadSelection = function (files) {
if (files && files.length == 1) {
var id = '';
var url = URL.createObjectURL(files[0]);
module.loadDocument(url,id);
}
};
Don't use a FileReader at all.
When you want to display a File (or a Blob) that is in the browser's memory or on user's disk, then all you need is to generate an URL that do point to this memory slot.
That's exactly what URL.createObjectURL(blob) does: it returns a Blob URI (blob://) that points to the data either in memory or on the disk, acting exactly as a simple pointer.
This method has various advantages over the FileReader.readAsDataURL() method. To name a few:
Store the data in memory only once, when FileReader would need it at reading, then generate a copy as an base64 encoded, and an other one at displaying...
Synchronous. Since all it does is to generate a pointer, no need to make it async.
Cleaner code.
const module = {
loadDocument: (url) => {
document.body.append(
Object.assign(
document.createElement('iframe'),
{ src: url }
)
)
}
};
document.querySelector('input[type=file]').addEventListener('input', function (evt) {
var file = this.files[0];
var url = URL.createObjectURL(file);
module.loadDocument(url);
});
<input type="file">
function PreviewFiles(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
//alert(e.target.result);
$('#pclogo').prop('src', e.target.result)
.width(200)
.height(200);
var base64result = e.target.result.split(',')[1];
$('input[name="logo"]').val(base64result);
};
reader.readAsDataURL(input.files[0]);
}
}
File objects have a readAsDataURL method.
Use that.
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.addEventListener("load", function () {
doSomethingWithAUrl(reader.result);
}, false);
if (file) {
reader.readAsDataURL(file);
}
I have a XML file like:
<People>
<Person>
<Name>John</Name>
<Lastname>Doe</Lastname>
<Age>30</Age>
</Person>
<Person>
<Name>Jane</Name>
<Lastname>Doe</Lastname>
<Age>29</Age>
</Person>
</People>
It is compressed to .zip file. I can read standalone (non zipped) file easily with:
HTML
<input type="file" id="unzipTest">
JavaScript
document.getElementById( 'unzipTest' ).addEventListener( 'change', unzipFile );
function unzipFile( event ) {
var eTarget = event.target;
var file = eTarget.files[ 0 ];
var reader = new FileReader();
reader.onload = function(){
var result = reader.result;
console.log( 'result: ', result );
};
reader.readAsText( file );
}
I correctly get XML file content in result variable.
The problem is when I am trying to extract a zip file containing that XML.
I am doing like so:
function unzipFile( event ) {
var eTarget = event.target;
var file = eTarget.files[ 0 ];
var zip = new JSZip();
zip.loadAsync( file, { optimizedBinaryString: true } ).then( function( fileContent ) {
var key = Object.keys( fileContent.files )[ 0 ];
var data = fileContent.files[ key ];
var compressedContent = data[ '_data' ].compressedContent;
console.log( 'compressed content: ', compressedContent );
var blob = new Blob( [ compressedContent ] );
var reader = new FileReader();
reader.onload = function(){
var result = reader.result;
console.log( 'result: ', result );
};
reader.readAsArrayBuffer( blob );
});
}
The compressedContent variable is some kind of Array (uint8array) with bits(?). I tried to read this Array by .readAsArrayBuffer(); method of reader with passing it a blob object. Unfortunately what I get is some weird ArrayBuffer with byteLength property which is a number.
What I do wrong and how to read extracted XML file properly?
I am using JSZip library: https://stuk.github.io/jszip/
Additionally - I need it to work with Internet Explorer 11
[SOLVED]
That solution helped me: https://stackoverflow.com/a/39964957/4983840
I am trying to read an image file and resize and upload it in Ionic2 on Android. My code works for small size images, but for images that are more than 3MB, the onloaded function is never called.
I really appreciate any help or insight as to why.
makeFileIntoBlob(_imagePath) {
return new Promise((resolve, reject) => {
window.resolveLocalFileSystemURL( _imagePath, fileEntry => {
fileEntry.file(file => {
var reader = new FileReader();
console.log('Reading the file!');
reader.onloadend = (e: any) => {
var img = document.createElement("img");
img.onload = () => {
//---> Only get here for small images!
var resizedImg = this.imgResizerSrvc.resize(img, 480, 480);
var imgBlob: any = this.dataURLtoBlob(resizedImg);
imgBlob.name = 'sample.jpg';
console.log('makeFileIntoBlob resolved!');
resolve(imgBlob);
}
//Will trigger img.onloadend
alert("about to trigger");
img.src = e.target.result; //----> This call only triggeres reader.onloadend for small images
alert("Done trigger");
};
reader.readAsDataURL(file);
});
});
});
}
As an alternative, I have also tried reading the file using the following:
img.src = (window.URL ? URL : window.webkitURL).createObjectURL( file );
or
img.src = (window.URL || window.webkitURL || window || {}).createObjectURL( file );
but none of these trigger img.onloaded().
There could be a limitation on the .length of the data URI
Length limitations
Although Firefox supports data URIs of essentially
unlimited length, browsers are not required to support any particular
maximum length of data. For example, the Opera 11 browser limited data
URIs to around 65000 characters.
You could use URL.createObjectURL() called on file, without using FileReader(), pass Blob created by .imgResizerSrvc.resize to File() to set the .name of the create File object.
makeFileIntoBlob(_imagePath) {
return new Promise((resolve, reject) => {
window.resolveLocalFileSystemURL(_imagePath, fileEntry => {
fileEntry.file(file => {
var component = /* reference to ionic2 component */ ;
var img = document.createElement("img");
img.onload = () => {
var resizedImg = component.imgResizerSrvc.resize(this, 480, 480);
var imgBlob = new File([resizedImg], "sample.jpg", {
type: "image/jpeg"
});
resolve(imgBlob);
};
img.src = URL.createObjectURL(file);
});
});
});
}