Multer not running when file is uploaded in Node.js with Express using FormData

I have been working on uploading a video file to a local folder using form, multer, express, and nodejs.

It seems that the video file successfully gets uploaded to the local folder each time I use the form. However, there is an issue with the code inside upload as it only executes occasionally, roughly once in every 5 attempts. For instance, the console.log('33'); within the app.post does not always appear. Surprisingly, the console.log('1') (located before upload) works consistently.

Below you can find the code for server.js:

var Express = require('express');
var multer = require('multer');
var mkdirp = require('mkdirp');
var app = Express();

var cors = require('cors');    
app.use(cors());
    
var Storage = ...
...

var upload = ...

app.post("/api", function(req, res) {
    console.log('1');

    upload(req, res, function(err) {
    console.log('33');
    if (err) {
             return res.end("Something went wrong!");
         }

    return res.status(200).end("File uploaded successfully!.");
  });

 });
...
...

Additionally, here is the snippet for app.js:

import React, { Component } from "react";
...
...

export default App;

Despite trying multiple suggestions from various sources, I am still unable to resolve this issue as I am relatively new to react/node js development.

Answer №1

Consider using async and await for improved performance.

server.js

const express = require('express');
const multer = require('multer');
const mkdirp = require('mkdirp');
const app = express();

const cors = require('cors');    
app.use(cors());
    
const storage = multer.diskStorage({
    destination: function(req, file, cb) {
        const dir = './client/public/video/';
        mkdirp(dir, function(err) {
            if (err) {
                console.error(err);
            }
            cb(null, dir);
        });
        console.log("Upload: saved to " + dir + file.originalname);
    },
    filename: function(req, file, callback) {
        callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
    }
});

const upload = multer({
    storage: storage
}).single("file");


app.post("/api", function(req, res) {
    console.log('1');

    upload(req, res, function(err) {
        console.log('33');
        if (err) {
            return res.end("Something went wrong!");
        }

        return res.status(200).end("File uploaded successfully!");
    });

});

app.get("/", function(req, res) {
    console.log('1');

    return res.status(200).json({});
});

const server = app.listen(9900, function () {
    console.log('app listening at 9900');
});

App.js

import React, { Component } from "react";
import axios from "axios";

class App extends Component {
    state = {
        file: null
    };

    handleOnChange = e => this.setState({ [e.target.name]: e.target.value });

    handleOnUploadFile = e => this.setState({ file: e.target.files[0] });

    handleOnSubmit = async e => {
        e.preventDefault();
        const formData = new FormData();

        formData.append("file", this.state.file);
        
        await axios.post("http://localhost:9900/api", formData, {
            headers: {
                'accept': 'video/mp4',
                'Accept-Language': `en-US,en;q=0.8`,
                'Content-Type': `multipart/form-data; boundary=${formData._boundary}`,
            }  
        })
        .then(res => console.log(res.data))
        .catch(err => console.error(err));
    };

    render() {
        return (
            <>
                <h1>{"<b>hello</b>".bold()}</h1>
                <form>
                    <input type="file" encType="multipart/form-data"
                        name="file"
                        accept="video/mp4"
                        onChange={this.handleOnUploadFile}/>
                    
                    <button type="submit" className="btn btn-danger" onClick={this.handleOnSubmit}>
                        Submit
                    </button>
                </form>
            </>
        );
    }
}

export default App;

Answer №2

Consider using a promise to enhance your upload function:

var Express = require('express');
var multer = require('multer');
var mkdirp = require('mkdirp');
var app = Express();

var cors = require('cors');    
app.use(cors());
    
var Storage = multer.diskStorage({
        destination: function(req, file, cb) {
        var dir = './client/public/video/';
        mkdirp(dir, function(err) {
        if(err) {
            console.error(err);
        }
        cb(null, dir);
    });
    console.log("Upload: saved to " + dir + file.originalname);
    },
        filename: function(req, file, callback) {
        callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
    }
});

var upload = multer({
    storage: Storage
  }).single("file");


app.post("/api", function(req, res) {
    console.log('1');
    
    upload(req, res).then((file, err) => {
    console.log('33');
    if (err) {
             return res.end("Something went wrong!");
         }

    return res.status(200).end("File uploaded successfully!.");
    })



 });

var server = app.listen(9000, function () {
  console.log('app listening at 9000');
});

Another approach could involve encapsulating the upload process within a promise:

var Storage = multer.diskStorage({
return new Promise((resolve, reject) => {
    destination: function(req, file, cb) {
            var dir = './client/public/video/';
            mkdirp(dir, function(err) {
            if(err) {
               reject(err)
            }
            cb(null, dir);
        });
        console.log("Upload: saved to " + dir + file.originalname);
        },
            filename: function(req, file, callback) {
            resolve(callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);)
        }
    })
    });

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

Looking for the best JSON database library?

Currently utilizing Node.js... Personally, I find SQL to be unappealing. My preference lies with JSON, as I desire to store my server data in that format. While I can utilize JSON.parse and .stringify, it seems like a suboptimal approach for larger appli ...

Implementing MouseEvents in Typescript React without having to pass them down to child elements

Is it possible to use Mouse Events on a whole React Element without having to pass it to a child element? I have been passing my handleEvent function to several functional components and now I want to know if it can be done without causing a TypeScript err ...

Understanding NPM Fundamentals and Installing Packages Locally

I am not very familiar with using Node and I have a question that may seem trivial to some, but I cannot find clear documentation on it. My limited skills in Node prevent me from investigating this further. I am currently following the instructions provid ...

What is the best method for incorporating Redux data into a navigator function? Alternatively, is there an alternative approach for building a dynamic navigation stack using incoming data?

When I log in as a user, the HomeScreen is where I am directed. This screen receives prompt values from our API and stores them in Redux. These values determine whether specific screens should be displayed alongside the Home Screen. I have created a funct ...

The password generated refuses to be saved

I've encountered an issue with saving a hashed password. Previously, when I saved the password as it was, everything worked fine. However, after implementing bcrypt for encryption, the process no longer works. The JSON response no longer includes the ...

Dealing with CORs Issue: Authentication with Google Oauth in React and Express using PassportJs validation

I'm having trouble setting up a React/Redux - NodeJs Express stack with Google OAuth authentication. Unfortunately, I keep encountering a CORs error in the console. Despite searching for solutions on Stack Overflow, such as CORS with google oauth and ...

How can I generate a list of JavaScript files to be included in a template for both production and development environments using Grunt?

I need a way to organize a list of JavaScript files in one central location, either within gruntfile.js or an external JSON file, and then dynamically implement it into a template for both development and production environments. List of JavaScript files: ...

What is the best method for updating a nested array within another nested array in an object using MongoDB?

There is a similarity between my issue and the one mentioned in this discussion LINK. However, my problem differs in the following way: { "_id": ObjectId("4d2d8deff4e6c1d71fc29a07"), "comments": [{ "na ...

npm local installation encounters initial failure

Context In my project, I have a package.json file containing multiple development dependencies. I prefer to use local installation by running npm install with the specified package.json node -v v0.10.26 npm -v 1.4.4 Windows 7 x32bit Issue Upon the i ...

What is the best way to automatically assign a class attribute to all form widgets in Django?

Whenever I create a form using Django, I want the input tag to automatically include a specific CSS class (form-control). Currently, I have to manually add lines of code in my forms.py file for each field like this: class InsertItem(forms.ModelForm): ...

Executing scripts during the build process in Next.js

Is there a recommended way to execute a script that creates static XML files during the build process? It would be ideal if these scripts were ES Modules so I can share code between them and my Next/React application. I believe I might need to customize t ...

While trying to set up a development server in Firebase, I mistakenly deleted my build folder

I recently encountered an issue with my Firebase project. While trying to set up a development server for my existing React web app that is already in production, I ran into some unexpected problems. firebase use bizzy-book-dev firebase init firebase ...

Include an Open OnClick event in the React/JSX script

We have a dynamic menu created using JavaScript (React/JSX) that opens on hover due to styling. My inquiries are: Instead of relying on CSS for the hover effect, where in the code can I implement an OnClick event to trigger the menu opening using Java ...

Having trouble accessing WPA3 encrypted Wi-Fi networks with the node-wifi npm package

Struggling to connect to a WiFi network secured with WPA3 encryption using the 'node-wifi' package. Unfortunately, it seems that 'node-wifi' does not support WPA3 encryption. For more details about 'node-wifi', check out its n ...

Encountering 503 errors with Heroku while making asynchronous API calls in my React application

Almost at the finish line with my project! The coding part was a breeze, but deployment is proving to be quite the nightmare. I've managed to get most of it deployed, but now the app is experiencing timeouts on API calls, even though they work perfect ...

None of the NPM commands are working due to an error stating: "TypeError: Class extends value undefined is not a constructor

For years, I've had no issues using n to install node. Recently, on my Big Sur mac, I decided to update from v14.17.6 to v16 without any problems. Now when I check the version with node -v, it shows "16.13.1." However, after the update, every npm com ...

Tips for sidestepping act() when making modifications to sub components

I'm using the Select component from patternfly and facing a dilemma while testing it. To change the selection, I found that I can make the tests pass without the need for use act() messages by following this approach: await waitFor(() => { user ...

Having difficulty transitioning a function with a promise from JavaScript to TypeScript

I am currently in the process of transitioning my existing NodeJS JavaScript code to TypeScript for a NodeJS base, which will then be converted back to JavaScript when running on NodeJS. This approach helps me maintain clear types and utilize additional fe ...

Struggling to render images within a child component in a React application when passed as a prop from the parent component

Currently immersed in a React project, here is the structured layout of my work: public index.html src App.js images facebook.png image.PNG linkedin.png profile.png twitter.png Profile Intro profileIntro.js data data.js Within App.js, I import ...

What is the best way to group an array based on a dynamic key?

My goal is to group values in an array by a given ID. I've attempted a method for this, but it's not working for dynamic keys. Here is the current array: let employees = [{"employeeDetail": [{"empID": "XXYYZZ11"," ...