Search code examples
javascriptthree.jslocalhostsame-origin-policy

Importing 3d model in three.js at runtime from localfile


I am trying to upload a 3d model from local file in runtime, but facing CORS error message. I have used http-server for uploading fixed models at start, but if I want to upload random objects from my local files to the scene, what is the best method to avoid CORS error?

For loading, I have used "OBJLoader" from https://threejs.org/docs/#examples/loaders/OBJLoader.


Solution

  • You can use a drag'n'drop approach similar to the three.js editor to load files from your computer into the app. The idea is to add an event listener to the drop event, extract the files from the respective event object and then use FileReader to read the actual content. When this loading process has finished, you can directly use OBJLoader.parse() in order to create the actual 3D objects.

    Check out the following code sections of the editor to better understand this workflow.

    • Handle drop event.

    https://github.com/mrdoob/three.js/blob/b524f4bca95169a2b197f8a68058e6c28abf416d/editor/index.html#L284-L290

    • Process the file list since it's possible to drag'n'drop multiple objects at once.

    https://github.com/mrdoob/three.js/blob/b524f4bca95169a2b197f8a68058e6c28abf416d/editor/js/Loader.js#L12-L43

    • Use FileReader and the respective loader (in your case OBJLoader) to load and parse the actual file. The linked method handles many different 3D formats. Just search for the OBJ part.

    https://github.com/mrdoob/three.js/blob/b524f4bca95169a2b197f8a68058e6c28abf416d/editor/js/Loader.js#L45

    three.js R104