"Error: Multer is Unable to Read the Undefined File

Despite my best efforts, I am unable to get multer's file upload feature to work. Despite studying numerous tutorials and guides on YouTube, as well as diving into countless StackOverflow threads, I still struggle to make it function properly through Postman.

This issue pertains to the route /image-upload.

Below is the complete code snippet:

const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const passport = require('passport');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const multer = require('multer');

const fileUpload = require('express-fileupload');

let path = require('path');


var storage = multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, __dirname + '../uploads')
    },
    filename: (req, file, cb) => {
      cb(null, file.fieldname + '-' + Date.now())
    }
});

var upload = multer({storage: storage});

router.post('/', upload.single('image'), (req, res, next) => {
    let file = req.file;
    console.log(req.file);
    console.log(req.files);
    if (!file) {
        return res.json({nofile: 'please upload a file'})
    }
})

module.exports = router;

The size of the file being uploaded is not the problem, as it is only 46KB in size. Strangely, when I log `req.file`, it returns undefined. However, when I log `req.files`, I do receive the full data details. When using Postman with form-data correctly set up for the POST route, it simply returns a json error, almost as if multer is not recognizing or reading the file at all. In Postman, I am ensuring that I am using form-data for the POST request, and the field name for the file is set to 'image', matching what is specified in the POST route.

Answer №1

Issue resolved! The culprit was express-fileupload. When utilizing express-fileupload in the file, it takes over req.file which prevents Multer middleware from accessing it. Removing that allowed me to rectify the problem and successfully upload the file.

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

Using setTimeout() does not work correctly when trying to call nested functions

I've written a timeout function that looks like this: setTimeout(this.logout, 1000); Here's the login method: logout() { this.auth_token = ""; this.loggedIn = false; this.emitLogedInStatusChange(); } isLoggedIn() { return this ...

Passing PHP values to JavaScript and then to AJAX requires using the appropriate syntax and techniques for

Currently, I am populating a table with data retrieved from my database. Here is a snippet of the code: <?php //mysqli_num_rows function while($row=mysqli_fetch_array //I know this may be wrong, but that's not the point echo "<tr><t ...

Error encountered when attempting to retrieve HTML content from localhost using AJAX

Attempting to insert HTML code into a div element using ajax, similar to how it's done with an iframe. Testing this out locally first to avoid Same Origin Policy complications. The web application is currently hosted on a wamp server. There are two ...

Break out of the Array.map() iteration

Below is the code snippet I am working with: const getCompanies = async (searchURL) => { const html = await rp(baseURL + searchURL); const businessMap = cheerio('a.business-name', html).map(async (i, e) => { const phone = ch ...

Having difficulty changing the visibility of a div element

I am currently working on a project that involves jQuery and ASP.Net. My main goal is to create a button that can hide/show a div using jQuery. Below is the code that I have implemented: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLI ...

Attempting to establish a means to switch between languages

Currently, I am in the process of implementing a language switch feature for a website project that I am currently working on. This feature will allow users to seamlessly switch between English, Latvian, and Norwegian languages. To achieve this functionali ...

Ways to eliminate double slashes from URL in Next Js. Techniques for intercepting and editing a request on the server side using getServerSideProps

Looking to manipulate a server-side request - how can this be accomplished? http://localhost//example///author/admin/// The desired output is: http://localhost/example/author/admin/ In Next Js, how can duplicate slashes in a URL be eliminated and req ...

Restricting the time frame in HTML 5

My form includes an input field with the type date <input type="date" id="datepick" name="mybirthday" placeholder="Birthdate(MM/DD/YYYY)" /> I am looking to restrict the date range that users can select. I specifically do not want users to be able ...

Enabling withCredentials in Angular 6 for every HttpClient request is crucial for maintaining consistent authentication and

Is there a method to set { withCredentials: true } as the default for every httpclient call, instead of having to add it manually each time? import { HttpClient } from '@angular/common/http'; ... constructor(private httpclient: HttpClient) { } ...

Is there a way to automatically redirect my login page back to the original page in case of login failure?

I'm currently working on a basic login page using express.js + E.js. If the login credentials are incorrect, I have a variable badLogin that is triggered (see below). However, my goal is to redirect the website back to the login page instead of remai ...

Encountered an issue with AWS S3: unable to retrieve the certificate from the local issuer

After completing my Protractor test suite execution, I am encountering an error while trying to upload my HTML result file to AWS S3 using JavaScript in my automation script. Can someone assist me in resolving this issue? static uploadtoS3() { con ...

Struggling to understand how to personalize a D3 generated graph

Currently, I am utilizing react-d3 instead of the Plotly react wrapper due to some bugs in the latter. My issue now lies in understanding the d3 API as I am unable to fully grasp it. I have successfully created a scatter plot similar to the one shown on ...

How can we use jQuery to hide a selected option from a dropdown menu and move it to another dropdown menu?

<select> <option value = "volvo" > Volvo < /option> <option value = "saab" > Saab < /option> <option value = "vw" > VW < /option> <option value = "audi"> Audi < /option> </select> ...

Mongoose has identified a cyclic dependency within the system

I'm facing "cyclic dependency detected" errors in my Express/Mongoose app and after investigating, I've narrowed it down to one of these files. app.js var express = require('express'); var mongoose = require('mongoose'); mo ...

Secure messaging with MERN technology and socket.io

Currently in the process of developing my very own private chat application using the MERN stack combined with socket.io. I've got the ability to successfully send private messages to specific users; however, I'm facing an issue where I can&apos ...

The autoRemoveInterval feature of connect-mongo is malfunctioning and not functioning as intended

Here is the code snippet that I am using with express.js and express-session: app.use(session({ store: new MongoStore({ mongooseConnection: db, autoRemove: 'interval', autoRemoveInterval: 1 // 1 minute (min) }), secret: 'so ...

Conflicting Angular components: Sorting tables and dragging/dropping table rows

In the current project I'm working on, I've integrated both angular table-sort and angular drag-drop. However, I ran into an issue where dragging a row and attempting to drop it onto another row causes the table sort to forcefully rearrange the r ...

Using Strapi to run basic raw SQL queries with MySQL

Trying to execute this query in my test but struggling with the correct syntax. return strapi.connections.default.raw(` delete from nurses; delete from users_permissions_user;`); }); Since this is not using PostgreSQL and MySQL ...

Retrieving the current window handle using Selenium WebDriver in Javascript

After receiving assistance from engineering, I have made some modifications to my code for grabbing the new window handle. Here is the final version: localdriver = @driver @driver.getAllWindowHandles() .then (handles) -> localdriver.switchTo().wind ...

Modifying array elements in JavaScript without explicit instructions

I am relatively new to Javascript and seem to be encountering a rather puzzling issue that I'm unable to resolve. Currently, I have two classes: Country and PPM_Data. The Country class contains parameters such as name, area, ppm, etc., along with a f ...