In this tutorial, nosotros are going to acquire how to upload a unmarried file in React app. We will also learn to shop image files in the MongoDB database using the Node server.

Uploading image files is a 24-hour interval to mean solar day task of a web developer, if yous are new to React, then this tutorial has the answer which you are looking for.

We will larn to upload single image file and store that file in the MongoDB database using Node and React.js. We will learn to create a customer-side bones React app, along with that we will also create a file upload API with Express, Multer, and other Node packages.

React Node Multer File Upload Example

  • Step i: Install React App
  • Step 2: Create React File Upload Component
  • Step 3: Create Node Server
  • Pace 4: Create Schema
  • Step 5: Fix Express Routes
  • Footstep half dozen: Prepare upwardly Server Js
  • Stride seven: Exam React File Upload API
  • Step 8: Build React Single File Upload

React Js 16 File Upload with Node Server

In the very first step, we install and set upwards React app for file upload demo.

Install React App

Enter the post-obit command in your terminal and press enter.

                  npx create-react-app react-node-file-upload                

Become to the project folder:

                                      cd                    react-node-file-upload                

Start your React app in the spider web browser:

                                      npm                    starting time                

View project on this URL: localhost:3000

Install Bootstrap iv in React app.

                                      npm                    install                    bootstrap --save                

Include bootstrap.min.css in src/App.js file:

                                      import                    React                    from                    'react'                    ;                    import                    '../node_modules/bootstrap/dist/css/bootstrap.min.css'                    ;                    function                    App                    (                    )                    {                    return                    (                    <div className=                    "App"                    >                    <h2>React File Upload Demo<                    /h2>                    <                    /div>                    )                    ;                    }                    export                    default                    App;                                  

Create React File Upload Component

Caput over to src > components directory and create a dissever file past the proper name of files-upload-component.js.

                                      import                    React,                    {                    Component                    }                    from                    'react'                    ;                    export                    default                    grade                    FilesUploadComponent                    extends                    Component                    {                    render                    (                    )                    {                    return                    (                    <div className=                    "container"                    >                    <div className=                    "row"                    >                    <form>                    <h3>React File Upload<                    /h3>                    <div className=                    "form-group"                    >                    <input type=                    "file"                    /                    >                    <                    /div>                    <div className=                    "form-grouping"                    >                    <button className=                    "btn btn-master"                    type=                    "submit"                    >Upload<                    /button>                    <                    /div>                    <                    /form>                    <                    /div>                    <                    /div>                    )                    }                    }                                  

Add together FilesUploadComponent in App.js template.

                                      import                    React,                    {                    Component                    }                    from                    'react'                    ;                    import                    '../node_modules/bootstrap/dist/css/bootstrap.min.css'                    ;                    import                    './App.css'                    ;                    import                    FilesUploadComponent                    from                    './components/files-upload-component'                    ;                    form                    App                    extends                    Component                    {                    return                    (                    )                    {                    return                    (                                                                  <div                      className                                              =                        "App"                                            >                                                                                                                              <                        FilesUploadComponent                                            />                                                                                                                              </div                      >                                        )                    ;                    }                    }                    consign                    default                    App;                                  

React File Upload

Create Node Server

Let'due south build the server with Node, Express, MongoDB and Multer for React file upload tutorial. Create the backend folder inside the React project.

Execute control to generate backend folder and get into the project folder.

                                      mkdir                    backend                    &&                    cd                    backend                

Build separate package.json file for Node server.

                                      npm                    init                

We will use post-obit node modules to build Node/Express server:

NPM Particular
Express A web application framework for Node.js.
MongoDB NoSQL Database based on document and collection format.
CORS Supports Access-Command-Allow-Origin CORS header.
bodyParser A trunk parsing middleware for Node.js.
uuid Simple, fast generation of RFC4122 UUIDS.
Multer A Node.js middleware handles multipart/course-data, best used of file uploading.

Run command to install NPM packages:

                                      npm                    install                    mongoose express cors body-parser uuid@^3.4.0 multer                                  

Install nodemon to machine-restart the node server, whenever it detects change in the server files.

Create Schema

Create a backend > models directory and create a fresh file within of it and proper name information technology User.js.

                                      const                    mongoose                    =                    crave                    (                    'mongoose'                    )                    ;                    const                    Schema                    =                    mongoose.Schema;                    const                    userSchema                    =                    new                    Schema                    (                    {                    _id:                    mongoose.Schema.Types.ObjectId,                    profileImg:                    {                    type:                    String                    }                    }                    ,                    {                    drove:                    'users'                    }                    )                    module.exports                    =                    mongoose.                    model                    (                    'User'                    ,                    userSchema)                                  

Nosotros declared profileImg value with String information type forth with Mongoose _id in Mongoose schema file.

Set Limited Routes

Create a backend > routes folder and create a new file inside of information technology and proper name it user.routes.js.

                                      let                    express                    =                    require                    (                    'express'                    )                    ,                    multer                    =                    require                    (                    'multer'                    )                    ,                    mongoose                    =                    require                    (                    'mongoose'                    )                    ,                    uuidv4                    =                    require                    (                    'uuid/v4'                    )                    ,                    router                    =                    express.                    Router                    (                    )                    ;                    const                    DIR                    =                    './public/'                    ;                    const                    storage                    =                    multer.                    diskStorage                    (                    {                    destination                    :                    (                    req,                      file,                      cb                    )                    =>                    {                    cb                    (                    nothing                    ,                    DIR                    )                    ;                    }                    ,                    filename                    :                    (                    req,                      file,                      cb                    )                    =>                    {                    const                    fileName                    =                    file.originalname.                    toLowerCase                    (                    )                    .                    split                    (                    ' '                    )                    .                    join                    (                    '-'                    )                    ;                    cb                    (                    zero                    ,                    uuidv4                    (                    )                    +                    '-'                    +                    fileName)                    }                    }                    )                    ;                    var                    upload                    =                    multer                    (                    {                    storage:                    storage,                    fileFilter                    :                    (                    req,                      file,                      cb                    )                    =>                    {                    if                    (file.mimetype                    ==                    "image/png"                    ||                    file.mimetype                    ==                    "epitome/jpg"                    ||                    file.mimetype                    ==                    "epitome/jpeg"                    )                    {                    cb                    (                    goose egg                    ,                    true                    )                    ;                    }                    else                    {                    cb                    (                    nil                    ,                    false                    )                    ;                    return                    cb                    (                    new                    Error                    (                    'Only .png, .jpg and .jpeg format allowed!'                    )                    )                    ;                    }                    }                    }                    )                    ;                    // User model                    let                    User                    =                    require                    (                    '../models/User'                    )                    ;                    router.                    post                    (                    '/user-profile'                    ,                    upload.                    unmarried                    (                    'profileImg'                    )                    ,                    (                    req,                      res,                      next                    )                    =>                    {                    const                    url                    =                    req.protocol                    +                    '://'                    +                    req.                    get                    (                    'host'                    )                    const                    user                    =                    new                    User                    (                    {                    _id:                    new                    mongoose.Types.ObjectId                    (                    )                    ,                    proper name:                    req.body.proper name,                    profileImg:                    url                    +                    '/public/'                    +                    req.file.filename                    }                    )                    ;                    user.                    salvage                    (                    )                    .                    then                    (                    upshot                    =>                    {                    res.                    condition                    (                    201                    )                    .                    json                    (                    {                    message:                    "User registered successfully!"                    ,                    userCreated:                    {                    _id:                    outcome._id,                    profileImg:                    result.profileImg                    }                    }                    )                    }                    )                    .                    grab                    (                    err                    =>                    {                    panel.                    log                    (err)                    ,                    res.                    condition                    (                    500                    )                    .                    json                    (                    {                    error:                    err                    }                    )                    ;                    }                    )                    }                    )                    router.                    get                    (                    "/"                    ,                    (                    req,                      res,                      next                    )                    =>                    {                    User.                    find                    (                    )                    .                    then                    (                    data                    =>                    {                    res.                    status                    (                    200                    )                    .                    json                    (                    {                    message:                    "User list retrieved successfully!"                    ,                    users:                    data                    }                    )                    ;                    }                    )                    ;                    }                    )                    ;                    module.exports                    =                    router;                                  

Create backend > public folder, in this folder we will store all the epitome files uploaded by user.

Run command from the root of the backend projection.

                                      mkdir                    public                

Prepare Server Js

In this step, create a backend > index.js file and paste the following code in it. This file contains required server settings such as database, express configuration, PORT connectedness, etc.

                                      allow                    express                    =                    crave                    (                    'express'                    )                    ,                    mongoose                    =                    require                    (                    'mongoose'                    )                    ,                    cors                    =                    require                    (                    'cors'                    )                    ,                    bodyParser                    =                    require                    (                    'body-parser'                    )                    ;                    const                    api                    =                    crave                    (                    '../backend/routes/user.routes'                    )                    // MongoDB Configuration                    mongoose                    .                    connect                    (                    'mongodb://127.0.0.1:27017/mydatabase'                    )                    .                    then                    (                    (                    10                    )                    =>                    {                    panel.                    log                    (                                          `                      Connected to Mongo! Database name: "                                              ${ten.connections[                        0                        ]                        .name}                                            "                      `                                        )                    }                    )                    .                    catch                    (                    (                    err                    )                    =>                    {                    console.                    error                    (                    'Error connecting to mongo'                    ,                    err.reason)                    }                    )                    const                    app                    =                    express                    (                    )                    ;                    app.                    use                    (bodyParser.                    json                    (                    )                    )                    ;                    app.                    use                    (bodyParser.                    urlencoded                    (                    {                    extended                    :                    false                    }                    )                    )                    ;                    app.                    apply                    (                    cors                    (                    )                    )                    ;                    app.                    use                    (                    '/public'                    ,                    express.                    static                    (                    'public'                    )                    )                    ;                    app.                    use                    (                    '/api'                    ,                    api)                    const                    port                    =                    process.env.                    PORT                    ||                    4000                    ;                    const                    server                    =                    app.                    listen                    (port,                    (                    )                    =>                    {                    console.                    log                    (                    'Connected to port '                    +                    port)                    }                    )                    app.                    use                    (                    (                    req,                      res,                      next                    )                    =>                    {                    // Error goes via `adjacent()` method                    setImmediate                    (                    (                    )                    =>                    {                    side by side                    (                    new                    Error                    (                    'Something went incorrect'                    )                    )                    ;                    }                    )                    ;                    }                    )                    ;                    app.                    use                    (                    function                    (                    err,                      req,                      res,                      adjacent                    )                    {                    console.                    fault                    (err.message)                    ;                    if                    (                    !err.statusCode)                    err.statusCode                    =                    500                    ;                    res.                    status                    (err.statusCode)                    .                    send                    (err.message)                    ;                    }                    )                    ;                                  

Examination React File Upload API

In this footstep we will examination REST API which we merely created, earlier that we need to start the Node server. Follow the given beneath process to start the Node/Express server.

Run control to starting time the mongoDB.

                  mongod                

Run nodemon server past executing the post-obit command:

                  nodemon server                
Method API URL
GET http://localhost:4000/api
Postal service /api/user-profile

API base Url: http://localhost:4000/api

We tin test following API in Postman, below is the final result:

React File Upload API Testing

Build React Single File Upload

Let's build React File upload functionality, first install the React axios library.

Next, install Axios library, it helps in making Http request in React app.

                                      npm                    install                    axios                

Add the below lawmaking in src/components/files-upload.component.js file.

                                      import                    React,                    {                    Component                    }                    from                    'react'                    ;                    import                    axios                    from                    'axios'                    ;                    export                    default                    grade                    FilesUploadComponent                    extends                    Component                    {                    constructor                    (                    props                    )                    {                    super                    (props)                    ;                    this                    .onFileChange                    =                    this                    .                    onFileChange                    .                    bind                    (                    this                    )                    ;                    this                    .onSubmit                    =                    this                    .                    onSubmit                    .                    bind                    (                    this                    )                    ;                    this                    .state                    =                    {                    profileImg:                    ''                    }                    }                    onFileChange                    (                    e                    )                    {                    this                    .                    setState                    (                    {                    profileImg:                    due east.target.files[                    0                    ]                    }                    )                    }                    onSubmit                    (                    e                    )                    {                    eastward.                    preventDefault                    (                    )                    const                    formData                    =                    new                    FormData                    (                    )                    formData.                    append                    (                    'profileImg'                    ,                    this                    .state.profileImg)                    axios.                    post                    (                    "http://localhost:4000/api/user-profile"                    ,                    formData,                    {                    }                    )                    .                    then                    (                    res                    =>                    {                    panel.                    log                    (res)                    }                    )                    }                    return                    (                    )                    {                    render                    (                                                                  <div                      className                                              =                        "container"                                            >                                                                                                                              <div                      className                                              =                        "row"                                            >                                                                                                                              <form                      onSubmit                                              =                        {                        this                        .onSubmit}                                            >                                                                                                                              <div                      className                                              =                        "form-group"                                            >                                                                                                                              <input                      type                                              =                        "file"                                            onChange                                              =                        {                        this                        .onFileChange}                                            />                                                                                                                              </div                      >                                                                                                                              <div                      className                                              =                        "class-group"                                            >                                                                                                                              <button                      className                                              =                        "btn btn-primary"                                            blazon                                              =                        "submit"                                            >                                        Upload                                                                  </push button                      >                                                                                                                              </div                      >                                                                                                                              </form                      >                                                                                                                              </div                      >                                                                                                                              </div                      >                                        )                    }                    }                                  
  • We declared the constructor and set the profileImg state and bind the events.
  • Within the file input field, we passed the onChange event along with onSubmit method on the course.
  • In the onSubmit method, we manage the file value using FormData interface, and then we are making the HTTP POST request using the Axios post() method.

react-file-upload-6559-02

Conclusion

Finally, React File Upload with Node/Express Js Tutorial is over. In this tutorial, we learned to upload a single file in React app and shop the images in the MongoDB database using the Node server.