Employing multer in conjunction with superagent to enable file uploads from a React application

I am new to using multer and experiencing some difficulties with it.

My goal is to upload an image file from a react client using the superagent library to my server.

However, the req.file data always shows as undefined in my code:

On the server side :

const upload = multer({ 
    dest: 'uploads/' })
app.post('/uploadprofile', upload.single('profil'), (req, res) => {
        console.log(req.file);
        console.log(req.files);
        console.log(req.body);
        res.status(200).end()
})

And on the client side :

onUploadFile(e) {
        console.log(e.target.files[0])
        this.setState({
            img: e.target.files[0]
        }, () => {
            agent
            .post("http://localhost:3100/uploadprofile")
            .attach('profil', this.state.img, this.state.img.name)
            .set("Content-Type", "")
            .end((err, res) => {
                console.log(err)
                console.log(res)
                console.log("send")
         })
        })
    }


render() {
return (
    <input id="file" type="file" accept="image/*" name="profil" className="inputButton" onChange={this.onUploadFile}/>
)
}

I had to override the content-type in my superagent request or else JSON data would be sent instead.

Despite making these changes, the req.file remains undefined on the server side.

Any help or suggestions would be greatly appreciated!

Answer №1

The problem lies in the superagent call you are making. You can refer to this helpful page for more information:

As mentioned on the page:

When using .field() or .attach(), do not utilize .send() and avoid setting Content-Type as it will be set correctly for you.

Therefore, it is important to remove

.set("Content-Type", "")
, and structure your code like this:

      await superagent
        .post(url)
        .withCredentials()
        .accept('application/json')
        .field('lets_try', 'ok!')                 // values from form fields
        .attach('staff', event.target.files[0]);  // file being uploaded

Upon receiving the single file on the server side, make sure to convert its buffer to a string if textual data is expected:

  console.log(`Uploaded req.body=${JSON.stringify(req.body)}`);
  console.log(`         req.file=${JSON.stringify(req.file, null, 2)}`);
  console.log(`req.file=${req.file.buffer.toString()}`);

You should see the following output:

Uploaded req.body={"lets_try": "ok!"}
         req.file={
   "fieldname": "staff",
   "originalname": "test.json",
   "encoding": "7bit",
   "mimetype": "application/json",
   "buffer": {
     "0": 10,
     "1": 98,
     "2": 111,
     "3": 98,
     "4": 10,
   },
   "size": 5,
 }
req.file=
 bob

In case your file content turns out to be bob :-)

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

What could be the reason behind the child component updating without triggering a re-render in Reactjs?

I am encountering an issue with my main component and child chart component. Even though the main component updates the state of the child chart component upon connecting to a websocket, the chart does not redraw as expected. Interestingly, when I click on ...

Error: Unable to modify a property that is marked as read-only on object '#<Object>' in Redux Toolkit slice for Firebase Storage in React Native

Hey there! I've been working on setting my downloadUrl after uploading to firebase storage using Redux Toolkit, but I'm facing some challenges. While I have a workaround, I'd prefer to do it the right way. Unfortunately, I can't seem to ...

"Could you please provide me with further details on how to use sequelize

I recently started working with node js and I used sequelize-auto to generate the models. However, I encountered an error when following the guidance provided in this link https://github.com/sequelize/sequelize-auto. If you need further clarification on th ...

How to prevent npm from being accessed through the command prompt

I recently began working on a ReactJs project. However, I am facing an issue where after starting npm in Command Prompt, I am unable to enter any text. Should I close the cmd window or is there a way to stop npm? You can now access your project at the fol ...

Ways to adjust text color after clicking on an element

Just a heads up, I didn't write all of the web-page code so I'm not exactly sure what pdiv is. But I want to see if I can fix this small issue [making text color change when clicked on to show which section you're reading]. This particular ...

Having difficulty using the forEach() method to loop through the array generated by my API

During my troubleshooting process with console.log/debugger, I discovered that I am encountering an issue when attempting to iterate over the API generated array in the addListItem function's forEach method call. Interestingly, the pokemonNameList ar ...

What is the best method for incorporating multiple collections in the get() function?

My code for university.js const mongoose = require('mongoose'); const UniversitySchema = mongoose.Schema({ worldranking:String, countryranking:String, universityname:String, bachelorprogram:String, masterprogram:String, ...

Implementing login functionality in an Angular application with the help of Kinvey.Social and utilizing the Promise API

I have been utilizing the Kinvey HTML5 library in an attempt to create a client-side application that integrates Google identities for Login. While the Oauth transaction appears to be functioning properly, I am encountering an issue with toggling the visib ...

What are the steps to resolve the "undefined cannot read property push" error in Node.js?

While attempting to learn Nodejs, I created a simple app. However, when I run "nodemon index.js" in the command prompt, I encountered the following error: TypeError: Cannot read property 'push' of undefined The app crashed and is now waiting for ...

JavaScript accordions failing to open

I've encountered an issue with my website that includes JS accordions. Strangely, they are not opening on the live site, but they function properly on Codepen. I checked the console in Chrome and found no error messages, however, when I looked at the ...

When filling options within an optgroup in a selectbox, the data for each option may override one another

UPDATE: I made a change in my code: $('select[name=productSelect]').setOptions(["All products|ALL", "Products visible to all|VISIBLETOALL=1"]); I updated it to: $('select[name=productSelect]').prepend(["All products|ALL", "Product ...

Tips for retaining form data after validation failure in a node.js application

Currently, I am working on validating form data using express validator. To keep the form fields populated even after a validation failure, I have split my routes and controllers into separate files. The validation process is being handled by express valid ...

What is the best way to ensure that one method waits for another method to complete before proceeding?

Below is a React method that needs completion for uploading images to cloudinary and setting the URL in state before executing the API call addStudent. The order of execution seems correct at first glance, but the last API call crashes due to base64 data n ...

Ways to solely cache spa.html using networkfirst or ways to set up offline mode with server-side rendering (SSR)

I am facing an issue with my application that has server-side rendering. It seems like the page always displays correctly when there is an internet connection. However, I am unsure how to make Workbox serve spa.html only when there is no network available. ...

What is the process for removing a document attribute in Sanity iO?

I have a collection of objects within my Sanity Document named Images which includes Comments An example comment object in the comments array looks like: { "_key": "6510dc79cf8b", "comment": "Hello world" ...

Resolving problems with jQuery auto-populating select dropdowns through JSON data

I am facing an issue with auto-populating a select dropdown using jQuery/JSON data retrieved from a ColdFusion CFC. Below is the code snippet: $(function(){ $("#licences-add").dialog({autoOpen:false,modal:true,title:'Add Licences',height:250,wid ...

Exploring the angular js repeater component's context menu options

In one of my current projects, the client has specifically requested a right-click menu feature. However, the challenge lies in ensuring that the function triggered by the menu options has access to relevant information from the model. For instance, you ...

Executing XSS Reflected Attack by Loading an External JS Script via POST Parameter

Experimenting with XSS attacks on my vbox machines, just for kicks! I have two .html files - one works and the other doesn't. The file that works contains: <html> <head></head> <body> <form method="post" action=&q ...

The GM_xmlHttpRequest POST method is not functioning properly when called within an event listener

My simple goal is to intercept xmlHttpRequests sent by a page and send them to my local server for logging in a text file. However, Ajax calls do not work in event listeners. I have tried various solutions all day long without success. Here is the code sni ...

Error encountered while adding x-ray-scraper to project using Npm

I am currently working on a Vue application and utilizing the x-ray-scraper library. However, when I attempt to run npm run serve in the terminal to preview the application locally, I encounter the following error: This dependency was not found: * _http_c ...