Reputation: 1247
I need to load any GLTF Model in ThreeJS the user wants to display. That means I have a file input tage where the user can click and then choose a gltf-file he wants to upload from his file browser:
<input id="selectedModel" type="file">
As soon as the user has selected a model I want to use the file directly and display it in ThreeJS, the problem is I do not know how I can use the selected file right of the bat, without first saving it on the server.
I've tried doing it like this:
const uploadedFile = document.getElementById("selectedModel").files[0]
loadGLTF( uploadedFile , function ( gltf ) {
model = gltf.scene
})
However this gives me an error:
url.lastIndexOf is not a function
I've also tried document.getElementById("selectedModel").value
but this gives me a fakepath
and ThreeJS cannot access this for some security reasons. What's the solution to this? Nothing I tried worked so far.
How can I display the model directly from the selected file in the input tag?
Upvotes: 1
Views: 2316
Reputation: 825
GLTFLoader does not accept files, you need to pass in a URL.
You can create local temporary URLs from File
or Blob
objects and pass them in like this
const uploadedFile = document.getElementById("selectedModel").files[0]
const url = URL.createObjectURL(uploadedFile);
loadGLTF( url, function ( gltf ) {
model = gltf.scene;
URL.revokeObjectURL(url);
}, function (){ }, function (){
URL.revokeObjectURL(url);
});
Assuming loadGLTF
is same as GLTFLoader.load()
. Second callback is for progress, third for error.
Make sure to revoke the URL even after failure.
Upvotes: 4