How to load an obj file along with its mtl dynamically using input of type file

Hello!

I am trying to render a model(xyz.obj file) along with its material.
I have used an input tag to select all files (obj, mtl and all other required files that mtl needs).

Since I can use parse function of OBJLoader and and MTLLoader to load obj and mtl file respectively but how can I give path to the parse function of MTLLoader. Since We can’t access local file system due to security reasons then how can we dynamically load models from local file system and render them in the browser?

Here is the piece of code:-

const files = e.target.files;
const scope = this;
const objFile = Array.from(files).find(file => file.name.toLowerCase().endsWith('obj'));
const mtlFile = Array.from(files).find(file => file.name.toLowerCase().endsWith('mtl'));
if (!objFile) {
    return;
}

new Promise((resolve, reject) => {

    if (mtlFile) {

        const reader = new FileReader();

        reader.readAsText(mtlFile);

        reader.onload = (e) => {
            const mtlLoader = new MTLLoader();

            const materials = mtlLoader.parse(e.target.result as string, '')

            // TODO:- Because path is empty it gives an error
            materials.preload()

            resolve(materials)
        }

        reader.onerror = (e) => {
            resolve(false)
        }

    } else {
        resolve(false)
    }

}).then((materials) => {

    if (materials) {

        const reader = new FileReader();

        reader.readAsText(objFile);

        reader.onload = (e) => {
            const objLoader = new OBJLoader()
            objLoader.setMaterials(materials as MTLLoader.MaterialCreator)
            const object = objLoader.parse(
                // resource URL
                e.target.result as string,
            )

            this.scene.add(object);

            
        }

    }

})
1 Like

Unless there’s a specific reason why you have to use obj format - you’d save yourself a lot of hassle by using .glb (binary glTF) format. They take up marginally more space and store all data (incl. materials and textures) in a single file. You can then load only one file using GLTFLoader.

1 Like

Due to some reason I have to use obj file format which I am gonna convert that using GLTFExporter and later use .glb format.