What is the best way to upload items by utilizing text input and a submission button?

I've been experimenting with loading obj files using three.js and webGL. Currently, I can load one object by directly modifying the code, but now I want to give users the ability to upload their own .obj files.

Here is the code snippet that I have so far. I've tried looking at various examples but I'm struggling to understand how to implement it correctly. Do I need to create a function to update it? And if so, would I have to redo everything in init? (When I say "redo," I mean more like copy/paste.) Is there a simpler way to accomplish this?

relevant parts of html file:

<form id="upload" method="get">
    .obj Upload: <input type="text" size="20" name="objfile" id="objfile">
    <!-- <input type="button" id="objsubmit" value="Send"> -->
</form>
<script type="text/javascript" src="cubemain.js"></script>

cubemain.js:

var scene, camera, renderer;
var container;
var objFile;

window.onload=function() {
    init();
    render();
}

function init() {

    // upload
    objFile = document.getElementById("objfile");

    // set up scene, camera, renderer
    scene = new THREE.Scene();

    var FOV = 70;
    var ASPECT = window.innerWidth/window.innerHeight;
    var NEAR = 1;
    var FAR = 1000;
    camera = new THREE.PerspectiveCamera(FOV, ASPECT, NEAR, FAR);

    // move camera back otherwise in same position as cube
    camera.position.z = 5;

    var light = new THREE.AmbientLight(0x101030);
    scene.add(light);

    var directionalLight = new THREE.DirectionalLight( 0xffeedd );
    directionalLight.position.set( 0, 0, 1 );
    scene.add( directionalLight );

    // use OBJLoader
    var loader = new THREE.OBJLoader();
    loader.load(objFile.value + ".obj", function(object) {
        scene.add(object);
    });

    renderer = new THREE.WebGLRenderer();
    renderer.setSize(.70*window.innerWidth, .75*window.innerHeight);
    document.body.appendChild(renderer.domElement);
    renderer.setClearColor(0xCC99FF, 1);

    var controls = new THREE.OrbitControls(camera, renderer.domElement);

}

function render() {
    requestAnimationFrame(render);

    renderer.render(scene, camera);
}

Answer №1

When it comes to this issue, the solution can vary depending on different factors. What worked for me was quite straightforward.

//Inside the html.html file
The element: <input type="text" id="inputFile">
<input type="button" id="submitBtn" onclick="loadTheFile()">

Upon clicking the button, a function within your JavaScript file will be activated. You just need to create the loadTheFile function and another function for loading the obj file. Here is a snippet of how it can be done:

//Remaining part of your JavaScript file
function loadTheFile(){
    //Retrieve the input text value which contains the file name
    var fileName = document.getElementById("inputFile").value;

    //Now, invoke another function named loadingFile with the received file name as an argument
    loadingFile(fileName);
}

function loadingFile(fileName){
//Utilize your loader by replacing the static path with the fileName as the new path
//Remember that the path passed into the loader should be relative to your main application.
var completePath = "models/" + filename;
//further loader operations

// Implement OBJLoader
var loader = new THREE.OBJLoader();
loader.load(completePath + ".obj", function(object) {
    scene.add(object);
});
}

I hope this explanation helps!

To enhance your code further, considering we have introduced a helper function called loadingFile, you can modify the loader section in your init() function like so:

before:

var loader = new THREE.OBJLoader();
loader.load(objFile.value + ".obj", function(object) {
    scene.add(object);
});

after:

loadingFile(objFile.value);

Follow up question: Is your code functioning correctly? Are you able to view the object as intended? Your code appears cleaner and more concise compared to what I usually use, so if it works well, I may consider incorporating your approach for improved readability. Thank you for your assistance, and I trust that my response proves beneficial to you! ^u^

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Register with your Facebook account - Angular 4 Typescript

After extensive searching, I have yet to find a clear answer to my question... This is my first time delving into the world of Social Networks. I am curious to know if there are options for Facebook and Twitter sign-ins using Typescript. It seems that Go ...

Initiate the IE driver in WebDriver NodeJS with the option to disregard protected mode settings and possibly introduce flakiness

I'm attempting to create a driver session using IE capabilities to bypass protected mode settings in Internet Explorer, but I'm unsure of the correct syntax. I've experimented with the following: var driver = new webdriver.Builder().wi ...

Unfortunately, I am unable to transmit a cookie using the res.cookie method in Express

After setting up the route to send a JWT with a cookie, I'm unable to see it in my browser. Here's the code for the route: router.post('/signup', async (req, res) => { const { email, password } = req.body try { const ...

Sending a multi-level property object to the controller in a post request

I am facing a challenge where I need to transfer an object from the view to the controller, and the model comprises a list of objects, each containing another list of complex objects. Let's consider the following models: public class CourseVm { p ...

Error: The Node.js server was unable to locate the requested resource, returning a status code of 404 indicating that the resource was not found

My web server is running on Node.js. var app = express(); app.use(express.static(PUBLIC_PATH)); server = require('http').createServer(app), io = require('socket.io').listen(server); I have set the public path to my application's ...

I am looking to insert an array of a specific type into a Postgres database using Node.js, but I am unsure of the process

query.callfunction('fn_create_mp_product', parameters, (err, result) => { if (err) { console.log(err) callback(err); } else { if (result.status == 'success') { callb ...

Issue with displaying Modal in ReactJS using hooks

I am currently utilizing react hook and react portal to create and display a modal. Here is the code snippet: Modal.tsx const modalRoot = document.getElementById('modal'); const Modal: React.FC<Props> = memo(({isOpen, toggle, children}) = ...

Validating emails using Vue.js

After spending a solid 24 hours working with Vue, I realize there may be some gaps in my knowledge. Despite my efforts to search for solutions, I suspect that my lack of understanding on basic principles is hindering me. One issue I've encountered is ...

Are there any downsides to utilizing the jQuery Load function?

I am in the process of creating a website that displays sensor data. I plan to incorporate a HighChart line chart to showcase this data. Since my website is relatively simple in terms of content, I have decided to consolidate all elements onto one page inc ...

Scale transformation - I am aiming for it to exceed the limits, yet it remains contained within

Currently, I am working on enhancing my carousel by implementing a zoom effect when hovering over the images. However, I have encountered an issue where the image gets hidden within the div container and doesn't overflow as expected. I tried adjusting ...

The error message "TypeError Cannot read properties of undefined (reading 'backdrop') - bootstrap v5.2.1 modal" is indicating that there is an

While working with the bootstrap modal, an error has been encountered ( TypeError Cannot read properties of undefined (reading 'backdrop') ), which has been logged in our bug tracker. However, attempts to replicate this error have been unsuccessf ...

Retrieving a PHP script from within a DIV element

I am seeking assistance to successfully load a PHP file from a DIV call. Below is the code I have used: <html> <head> </head> <body> <script class="code" type="text/javascript"> $("#LoadPHP").load("fb_marketing ...

Implement the Vue.js @click directive in a location outside of an HTML element

I've set up a link like this: <a href="#" @click="modal=true">Open modal</a> Here's the data setup: export default { data () { return { modal: false } } } Is there a way to trigger the cli ...

Guide on sending a PUT request using express.js

Currently delving into node.js and have a query regarding PUT requests I'm able to create an object and see it in the URL. However, I'm unsure of how to write a request to edit it - such as changing the price of a vehicle. Any guidance on writin ...

Steps to trigger a dialog to appear automatically within an Icon Menu with React Material UI

In my application, I have an icon menu implemented along with an array that contains the possible values for the items in the menu. Here is an example of how the array looks: listItems = { [ { label: 'ZERO', t ...

Discovering DOM elements positioned between two other well-established DOM elements can be achieved by utilizing a variety of methods

What is the most efficient and elegant way to select all elements between two specified elements using vanilla JavaScript? For instance, how can I target all elements between: <h2> and <hr> .. and the result should be an [ p, p, ul ] ... but & ...

Using Django to load a template and incorporate a loading spinner to enhance user experience during data retrieval

In my Django project, I need to load body.html first and then dashboard.html. The dashboard.html file is heavy as it works with python dataframes within the script tag. So, my goal is to display body.html first, and once it's rendered, show a loading ...

What is the best way to apply a row of decals to an item using Three.js?

I found This Example fascinating because it demonstrates the use of the 'pointerup' event to add decals to an object. Here is the code snippet showcasing this functionality: window.addEventListener( 'pointerup', function ( event ) { ...

Pressing an HTML button can enable and disable the pause and resume functions

Currently, I am working on an audio player where I need to implement functionality to pause and resume the playback. I have already set up the pause() and resume() functions in my script. The issue I am facing is related to the HTML button that triggers th ...

Using Ajax without implementing JavaScript

Is it possible to develop an application that utilizes Ajax without relying on JavaScript, allowing it to function even if JavaScript is disabled by the user in their browser? Are there any restrictions or limitations to consider? ...