Error: The formdata contains an unexpected field (Please upload an image)

I have been encountering the same error on the server side no matter what I do while trying to upload an image file. If anyone can point out what I might be missing, I would greatly appreciate it.

javascript:

        const filePicker = document.getElementById('takePhoto');
        const myFile = filePicker.files[0];
        var formData = new FormData;
        formData.append('myFile', myFile) 
        
        fetch(appURL+'onlineHelp/questionImage', {
            method: 'POST',
            body: formData
        })

Data sent via FormData:

myFile: (binary)

On the server side:

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

onlineHelp.post('/questionImage', upload.single("myFile"), (req, res, next)=>{
    res.send("received")
    next(
})

Error message:

MulterError: Unexpected field
    at wrappedFileFilter (C:\Users\annet\Documents\ALS homeworx API\node_modules\multer\index.js:40:19)
    at Busboy.<anonymous> (C:\Users\annet\Documents\ALS homeworx API\node_modules\multer\lib\make-middleware.js:114:7)
    at Busboy.emit (events.js:198:13)
    at Busboy.emit (C:\Users\annet\Documents\ALS homeworx API\node_modules\busboy\lib\main.js:38:33)
    at PartStream.<anonymous> (C:\Users\annet\Documents\ALS homeworx API\node_modules\busboy\lib\types\multipart.js:213:13)
    at PartStream.emit (events.js:198:13)
    at HeaderParser.<anonymous> (C:\Users\annet\Documents\ALS homeworx API\node_modules\dicer\lib\Dicer.js:51:16)
    at HeaderParser.emit (events.js:198:13)
    at HeaderParser._finish (C:\Users\annet\Documents\ALS homeworx API\node_modules\dicer\lib\HeaderParser.js:68:8)
    at SBMH.<anonymous> (C:\Users\annet\Documents\ALS homeworx API\node_modules\dicer\lib\HeaderParser.js:40:12)

Answer №1

If you're looking to upload images or files to a Node.js server, this code snippet might come in handy.

Here's the JavaScript:

    const formData = new FormData()
    formData.photo = file

    var res = await fetch('/your api', {
        method: 'PATCH',
        body: formData,
    })

On the server side, you'll need something like this:

   router.patch('/avatar', auth, async (req, res, next) => {
     if (req.files) {
      let photo = req.files.photo;
      if (photo.size < 3000000) {
         var random = Math.floor(Math.random() * 9999999 + 10);
         if (!photo.mv('./public/uploads/users/avatars/' + random + "_avatar." + photo.name.split('.').pop())) {
                return res.status(400).json({ "status": "error", "data": "server cann't upload" });
            }
            Users.findByIdAndUpdate(req.userId, { $set: { avatar: + random + "_avatar." + photo.name.split('.').pop(), update_in: Date.now() } }, function (err, user) {
                if (err) {
                    return res.status(400).json({ "status": "error", "msg": err });
                }
                Users.findById(req.userId).select("-password -role -sms -sms_time -__v").exec(function (err, user) {
                    return res.status(200).json({ "status": "success", "data": user }); //user update shod
                });
            });
        } else {
            return res.status(400).json({ "status": "error", "msg": "Photo size should be maximum 3MB" });
        }
    } else {
        return res.status(400).json({ "status": "error", "msg": "Image not found" });
    }
   });

To enable file uploads on your server.js app, include this code snippet:

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

    app.use(fileUpload({
      createParentPath: true
    }));

Answer №2

To properly handle the directory, it is recommended to present it in an object like

cb(null, { fieldName: "temp_upload" });

It's important to note that for a production application where files need to be accessed on the website, using an object store such as s3 or another provider is advisable. This is because Node is often run as a cluster, with each instance having its own thread pool and not communicating with others. Therefore, if a user uploads a file on one instance, other instances will not have knowledge of the file.

Multer has an s3 plugin that is quite easy to use. However, if you are only uploading and reading files within the same process in the node stack (e.g. uploading an XML file and then reading it in the same process), you should be fine without needing an object store.

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

Incorporate an image into the React state in order to showcase it within a personalized

Objective I am aiming to create a dropdown menu that allows users to select images instead of text. Context I have integrated a react dropdown component into my file, and it works well with text options. However, I am facing difficulties in displaying i ...

Shorten certain text in Vuetify

Here's an example of a basic select component in Vuetify: <v-select :items="selectablePlaces" :label="$t('placeLabel')" v-model="placeId" required ></v-select> I'm looking to apply a specific style to all selec ...

Why is my Node.js express application throwing a 404 POST error?

I am facing an issue while trying to build a node.js application with express. Whenever I attempt to log in and my index.ejs file sends a post request to the server, I encounter a 404 error. Being new to programming, I am seeking assistance from someone wh ...

Steps for resetting all Bootstrap JS controls:

On my Bootstrap website, I am dynamically loading HTML content using an AJAX jQuery script. The loaded content contains Bootstrap JavaScript controls such as dropdowns, tabs, and collapse elements. However, since these are loaded after the DOM event, none ...

Does this Loop run synchronously?

Recently, I crafted this Loop to iterate through data retrieved from my CouchDB database. I am curious whether this Loop operates synchronously or if async/await is necessary for proper execution. database.view('test', 'getAllowedTracker&ap ...

Angular throws an error when attempting to access a property that is undefined

I created the following angular template: <section class="section"> <div class="container"> <form [formGroup]="testForm"> <div class="columns is-multiline"> <div class="column is-2"> ...

Here is a step-by-step guide on how to use JQuery to swap out text with

Requesting assistance on displaying JSON values in a JQuery table with corresponding image icons. The JSON values include "Success", "Failed", and "Aborted" which should be represented by image icons named Success.png, Failed.png, and Aborted.png. Any guid ...

The Postman continues to send the request indefinitely, never stopping

Hey there, I'm diving into the world of node.js/express/postman and could really use a bit of help. Following an online tutorial, I've come up with the code below. When testing it with Postman, I encountered a strange issue. As soon as I include ...

Warning for pending changes prior to moving in Svelte

My current setup involves a Svelte application that includes form content. Whenever a modification is made within the form, an "unsaved change" alert can be triggered upon page refresh. However, when attempting to navigate to a different page using Svelt ...

Validating group radio buttons that have been checked

I possess: <div class="group"> <input type="radio" name="myradio" value="1">a <input type="radio" name="myradio" value="2">b </div> <div class="group"> <input type="radio" name="two" value="3">a <input ty ...

Collapse the Bootstrap Menu upon selecting a Link

I am working on a side menu with an offcanvas display feature. The current functionality is such that when the button is clicked, the canvas pushes left and opens the menu. However, I want the menu to collapse and close automatically when a link is selecte ...

Ways to customize date format based on locale in AngularJS

Currently using a German PC with browser locale set to de. Also installed the following JS library: <script src="//code.angularjs.org/1.5.6/i18n/angular-locale_de-de.js"></script> The issue is that {{mydate | date:'shortDate'}} stil ...

Vue displaying element tags without proper color rendering

Currently, I am using Vue3 in VS Code and encountering an issue where the colors of the Vue tags appear as white, making it difficult for me to differentiate between the template, script, and style tags. If you would like to take a look at the code sample ...

when executing the Express program, an error page is displayed

var express = require('express'); var app = express(); var bodyparser = require('body-parser'); var mongoose = require('mongoose'); books = require('./models/books.js'); mongoose.connect('mongodb://localhost/b ...

Updating React state manually before using the setState function

Currently, I'm delving into React JS and working on a basic todo list project. A snippet of my code looks like this: changeStatus(e, index) { this.state.tasks[index].status = e.target.value; this.setState((prevState) => ({ tasks: p ...

Acquire 2394 through the use of typescript

What could be causing this error? I have attempted different approaches, but the error persists without resolution Here is my code: function $sum(xor:string[]):string function $sum(xor:number[]):number { let xor_; if(xor instanceof String){ ...

Modify the AJAX data in Datatables without directly modifying the elements

I am currently working with a Datatable that is being populated through AJAX, and everything is going smoothly. However, I am looking for a way to include some shortcuts to send requests to the server. The issue lies in how I can modify the data being sent ...

The integration of angular 1.3.15 with html5mode for deeplinking, routing, and hash functionality

I have implemented html5mode true and included <base href="/"> within the head tag. Everything appears to be functioning properly at first, but upon page refresh, an error is encountered. The requested URL /updated_1/work was not found on t ...

Load Bootstrap CSS file externally on a website dynamically

Although my knowledge of JavaScript is limited, I am the recipient of a small web application from a friend that is being utilized by multiple companies. As each company requires specific modifications in the appearance and CSS of certain webpages, it can ...

Methods for retrieving and persisting the data from a particular row within a table using JavaScript or jQuery

Is there a way to store the selected row values of a table in an array of arrays using JavaScript / jQuery? Check out this JSFiddle I believe that we should listen for the event when the 'Show selected' button is clicked. For instance, in Java ...