Upload a file in React and send it to an Express server

Upload a file in React and send it to an Express server

react file upload
react axios file upload
react js multiple file upload example
react file upload codepen
multer
react upload image
express file upload
react-bootstrap file upload

I need to upload a file in React and then send it to an Express server (I'm new to Express so it's hard for me),

I succeed to upload the file in my React Component, but now I don't know how to send it to my back-end server made with Express.

What do I need to use ? Axios or Fetch ? Get or Post ? Thank you !

my App.js file (front-end)

uploadFile = () => {
const { currentFileName, currentFileType } = this.state;
if (currentFileName && currentFileType) {
  fetch('http://localhost:5000/upload/files', {
    method: "POST",
    headers: {
      'Content-type': 'application/json'
    },
    body: JSON.stringify(this.state)
  })
  .then((res) => res.json())
  .then(res => {
    this.setState({
      errorMessage: "",
      successMessage: `Votre fichier ${currentFileName} a bien été uploadé !`
    });
    console.log(res);
    console.log(res.data);
  })
} else {
  this.setState({
    errorMessage: "Veuillez choisir un fichier avant d'appuyer sur le bouton Upload !"
  });
}

}

and my server.js file (back-end)

const express = require('express');

const app = express();

const router = express.Router();

app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
next();
});

const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.post('/upload/files', (req, res) => {
    var fileName = req.body.currentFileName;
    var fileType = req.body.currentFileType;
console.log('Nom du fichier: ' + fileName + ' ' + 'Type du fichier: ' + fileType);
res.send(fileName + fileType);
});

const port = 5000;

app.listen(port, () => `Server running on port ${port}`);

I expect to get the state datas in localhost:5000/upload/files but when I go on the URL I have the message "Cannot GET /upload/files"

Can someone help me please ? Thank you !


You can use axios to upload the file.

const yourFile = file // Assume this is your file.

Now you need to add it to a form data.

const formData = new FormData();
formData.append('file', yourFile);

now:

axios.post('/yourEndpoint', formData).then(res => {
  //Now do what you want with the response;
})

In your NodeJS app:

app.post('/yourEndpoint', function(req,res){
  fs.readFile(req.files.file.path, function(err, data){
    // Do something with the data (which holds the file information)
  });
});

Upload a file in React and send it to an Express server, You can use axios to upload the file. const yourFile = file // Assume this is your file. Now you need to add it to a form data. Since you're trying to send a file, it's better to use a Post (quick tip : Get is used when you need to get data from server and Post is used when you need to post data to the server). In this tutorial, we are going to learn about file uploading in React with using Express as a backend. Creating Express Backend server. First, we are creating a post API using NodeJS & express, which helps us to upload the files like (images, pdf, etc) to the backend server.


Since you're trying to send a file, it's better to use a Post (quick tip : Get is used when you need to get data from server and Post is used when you need to post data to the server).

Then for express, you should look at multer wich is a middleware for handling multipart/form-data.

Finally, in your react, you juste need to send the file in a mutlipart form with fetch

How To Upload Files With React To A Node/Express Server, extname(file. originalname)}`; cb(null, newFilename); }, }); // create the multer instance that will be used to upload/save the file const upload = multer({ storage }); const app = express(); app. use(bodyParser. json()); app. I need to upload a file in React and then send it to an Express server (I'm new to Express so it's hard for me), I succeed to upload the file in my React Component, but now I don't know how to send it to my back-end server made with Express.


In your frontend grab your file

 <input type="file" id="inputGroupFile01" 
    onChange={(e) => this.onSelectImageHandler(e.target.files)}
/>

You must send the file to the server as a FormData as follows:

onSelectImageHandler = (files) => {
    const file = files[0];
    const formData = new FormData();
    formData.append('file', file)

    const config = {
        headers: {
            "Contetnt-Type":"multipart/form-data" 
        }
    };
}

Once you have your FormData setup, you can make the call with axios.

Then you need to install multer package on your server side $npm i -S multer, then on your server.js file.

const multer = require('multer');

You can configure multer just at the beginning after all requires.

const upload = multer({dest: 'public/uploads/'}).single('file');

Then in your route:

app.post('/upload/files', (req, res) => {
    upload(req,res, (err) => {
        const file = req.file
    const prevUrl = req.body.prevUrl.slice(21) //I use slice to cut the public part of the path, since mine is accessible from anywhere.
    if(!err){
        //here you could add some call to save the prevUrl "url of the file to called it later on your front"
        return User.findOneAndUpdate({_id:req.decoded.userId},{avatarUrl:avatarUrl}, (err, user) => {
            if(!err){       
                return console.log(err)
                })
                return res.json({success:true, message:"File has been successfully uploaded",avatarUrl:"http://localhost:3231/uploads/"+file.filename});
            }
            console.log(err);
        })
    }
    console.log(err);
    })
});

Hope it helps.

How to upload files in React with NodeJS & Express, Developing specific Backend server First, we're developing a submit API the usage of NodeJS & express, which enables us to upload the  Here we will only focus on client side technology React framework only. user will be provided a browse button to select a file and a button for uploading file into server. The button will be disabled by default until a user selects a file for uploading.


How to Upload Files with React and Node.js, How to Upload Files with React and Node.js We have a GET route to get the photos with findAll , a POST route for saving a Photo with create  Finally, React Multiple File Upload with Node/Express Tutorial is over. In this tutorial, we explored how to upload a multiple image files in the MongoDB database using the Node and Express server. In this tutorial, we explored how to upload a multiple image files in the MongoDB database using the Node and Express server.


Creating a File Upload Component with React, First, we need to create a basic express server in the server.js file. we require our upload.js file and register a route with the HTTP-post  File uploading means a user from a client machine wants to upload files to the server. For example, users can upload images, videos, etc on Facebook, Instagram. As with any programming problem, there are many ways to achieve this outcome. This article explains a simple way to implement the approach to upload a single file with React.


React Single File Upload Tutorial with Node, Express and Multer , React File Upload with Node/Express Js Tutorial - Learn to upload a className="btn btn-primary" type="submit">Upload</button> </div>  To upload the files to the server, we implement the "sendRequest" method. All this method does for now, is creating a new Promise. Inside of that promise, we create a new XMLHttpRequest and send that to the url of our file upload server using a post request and the file to upload wrapped into a FromData object.