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

A guide to testing redux API using Node.js

I'm diving into the world of nodejs and redux as a beginner. I managed to install node v7.10 on my computer. While reading through the Redux documentation, it mentioned that I should be able to test the action, reducer, and store API without a user in ...

Managing multiple sets of data in a structured form similar to an array

How Do I Send Form Data as an Array? Take a look at the code snippet below. I'm having trouble setting the index in product_attribute['index must be here']['key'] <tr v-for="index in attributes"> <td class="text-left ...

Using HTML and JavaScript to verify email addresses

I have been working on an "Email Validation" code, but it seems to be malfunctioning. I can't figure out why. Would you mind taking a look at it? Thank you. I suspect that the issue lies with this line document.getElementById("custEmail").onchange = ...

Interactive search functionality using jQuery

In the panel I have, I would like to include a search input field that allows users to type in a word. As soon as a match is found, that specific word will be highlighted within the panel while the other information disappears. ...

Generate a list of users using Angular in an efficient manner

I am working on creating a user list similar to the image provided below. I am using Angular and Bootstrap for the basics of this project. However, my concern is how to efficiently handle a large number of users. If the user count exceeds 10k, what would b ...

Replicating a row in a table without disrupting a button within the row

As a novice in the world of coding, I am currently embarking on a project to revamp an existing website. The task at hand involves creating a table with a built-in save/edit feature, which I have successfully implemented. However, I am facing a roadblock w ...

Angular with PHP Integration Success

I'm navigating the realms of Angular and PHP, understanding that Angular is client-side while PHP operates on the server. I'm curious if there's a way to merge these two technologies, as it's all quite unfamiliar territory for me. For ...

SignalR error: A type conversion issue has occurred where it is not possible to directly convert a task returning an object to a string

I'm encountering an issue with my C# hub class where the JavaScript code is returning a System.Threading.Tasks.Task instead of a string. I need help modifying the JavaScript method to return an actual string. Below is the hub class: public String ge ...

Linking chained functions for reuse of code in react-redux through mapStateToProps and mapDispatchToProps

Imagine I have two connected Redux components. The first component is a simple todo loading and display container, with functions passed to connect(): mapStateToProps reads todos from the Redux state, and mapDispatchToProps requests the latest list of todo ...

Can dynamic import be beneficial in a node.js environment?

As a newcomer to the world of node.js/express, I must say that I am thoroughly enjoying my experience with it so far. I have adopted ES6 syntax for imports in my project. Initially, when setting up my project, I defined all my routes as follows : app.get ...

Can you please guide me on how to convert pug (jade) to html using npm scripts?

Struggling to construct my package.json file, I find myself facing a challenge when it comes to writing scripts. "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build-css":"node-sass --output-style compressed -o bu ...

Merging two arrays together in JavaScript

Within my possession are two arrays: var g= [ { id: 36, name: 'AAA', goal: 'yes' }, { id: 40, name: 'BBB', goal: 'yes' }, { id: 39, name: 'JJJ', goal: 'yes' }, { ...

What is the syntax for creating a tally in Sequelize?

DISPLAY TOTAL COUNT OF VOLUNTEERS AND THEIR AGES FROM THE 'RED_CROSS_VOLUNTEERS' DATABASE GROUPED BY AGE; ...

When an element is dragged within the mcustomscrollbar container, the scroll does not automatically move downward

I am facing an issue where I have multiple draggable elements inside a Scrollbar using the mcustomscrollbar plugin. When I try to drag one of these elements to a droppable area located below the visible area of the scroller, the scroll does not automatical ...

Setting up Laravel with pjax

For the first time, I am experimenting with using pjax in combination with Laravel to enhance page loading speed. Since I am not well-acquainted with this technology yet, I have integrated this package into my project. Everything appears to be functioning ...

How to download an Excel file (xlsx) using AngularJS and WebApi

I am currently working on a project that requires me to download a report in xlsx format. Despite successfully generating the report file on the server and receiving it on the client side, I am facing an issue where the file is not opening and is resulting ...

explore the route with the help of jquery scrolling feature

Is there a way to implement scrolling functionality for tab headers similar to this demo? I have a list of elements within a div that I need to scroll like the tabs in the demo. I attempted to achieve this by setting the position of the inner elements to ...

I'm having trouble retrieving the request body in Postman

I am currently working on a controller function along with an endpoint: controller uploadSalesOrderFromExcel : async function (req,res) { console.log(req.body); if (!req.body.branchId) { return res.status(400).send({ Error: "B ...

Displaying buttons within a component's onPress function will reveal the most recent information. Utilizing React-N

Currently, I am working on loading a component that contains an array from redux (for example, test). I have successfully created buttons with the correct titles, however, there seems to be an issue with the onPress function not displaying the expected v ...

The Backbone model destruction URL fails to include the model's ID when trying to delete

I'm facing an issue in my app where I need to delete a model from a collection using "this.model.destroy" in my view, but it triggers a 405 response and the response URL doesn't include the model's id. According to the Backbone documentation ...