Dvir Shabi

1572411558

How to upload a file in the React application with Node, Express and Multer

In this tutorial, we are going to learn how to upload a single file in React app. We will also learn to store image files in the MongoDB database using the Node server. Uploading image files is a day to day task of a web developer, if you are new to React, then this tutorial has the answer which you are looking for.

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

React Js 16+ File Upload with Node Server

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

Install React App

Enter the following command in your terminal and press enter.

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

Go to the project folder:

cd react-node-file-upload

Start your React app in the web browser:

npm start

View project on this URL: localhost:3000

Install Bootstrap 4 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

Head over to src > components directory and create a separate file by the name of files-upload-component.js.

import React, { Component } from 'react';

export default class 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-group">
                            <button className="btn btn-primary" type="submit">Upload</button>
                        </div>
                    </form>
                </div>
            </div>
        )
    }
}

Add 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';

class App extends Component {
  render() {
    return (
      <div className="App">
        <FilesUploadComponent />
      </div>
    );
  }
}

export default App;

This is image title

Create Node Server

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

Execute command 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 following node modules to build Node/Express server:

This is image title

Run command to install NPM packages:

npm install mongoose express cors body-parser uuid multer


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

Set up MongoDB

Create a backend > database folder and create a new file inside of it by the name of db.js.

module.exports = {
   db: 'mongodb://localhost:27017/react-fileupload-db'
};

Create Schema

Create a backend > models directory and create a fresh file inside of it and name it User.js.

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
    _id: mongoose.Schema.Types.ObjectId,
    profileImg: {
        type: String
    }
}, {
    collection: 'users'
})

module.exports = mongoose.model('User', userSchema)

We declared profileImg value with String data type along with Mongoose _id in Mongoose schema file.

Set up Express Routes

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

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

Run command from the root of the backend project.

mkdir public


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(null, DIR);
    },
    filename: (req, file, cb) => {
        const fileName = file.originalname.toLowerCase().split(' ').join('-');
        cb(null, uuidv4() + '-' + fileName)
    }
});

var upload = multer({
    storage: storage,
    fileFilter: (req, file, cb) => {
        if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") {
            cb(null, true);
        } else {
            cb(null, false);
            return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
        }
    }
});

// User model
let User = require('../models/User');

router.post('/user-profile', upload.single('profileImg'), (req, res, next) => {
    const url = req.protocol + '://' + req.get('host')
    const user = new User({
        _id: new mongoose.Types.ObjectId(),
        name: req.body.name,
        profileImg: url + '/public/' + req.file.filename
    });
    user.save().then(result => {
        res.status(201).json({
            message: "User registered successfully!",
            userCreated: {
                _id: result._id,
                profileImg: result.profileImg
            }
        })
    }).catch(err => {
        console.log(err),
            res.status(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;

Set up Server Js

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


let express = require('express'),
    mongoose = require('mongoose'),
    cors = require('cors'),
    bodyParser = require('body-parser'),
    dbConfig = require('./database/db');

const api = require('../backend/routes/user.routes')

// MongoDB Configuration
mongoose.Promise = global.Promise;
mongoose.connect(dbConfig.db, {
    useNewUrlParser: true
}).then(() => {
    console.log('Database sucessfully connected')
},
    error => {
        console.log('Database could not be connected: ' + error)
    }
)

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(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 `next()` method
    setImmediate(() => {
        next(new Error('Something went wrong'));
    });
});

app.use(function (err, req, res, next) {
    console.error(err.message);
    if (!err.statusCode) err.statusCode = 500;
    res.status(err.statusCode).send(err.message);
});

Test React File Upload API

In this step we will test REST API which we just created, before that we need to start the Node server. Follow the given below process to start the Node/Express server.

Run command to start the mongoDB.

mongod

Run nodemon server by executing the following command:

nodemon server

This is image title

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

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

This is image title

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 code in src/components/files-upload.component.js file.


import React, { Component } from 'react';
import axios from 'axios';

export default class 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: e.target.files[0] })
    }

    onSubmit(e) {
        e.preventDefault()
        const formData = new FormData()
        formData.append('profileImg', this.state.profileImg)
        axios.post("http://localhost:4000/api/user-profile", formData, {
        }).then(res => {
            console.log(res)
        })
    }


    render() {
        return (
            <div className="container">
                <div className="row">
                    <form onSubmit={this.onSubmit}>
                        <div className="form-group">
                            <input type="file" onChange={this.onFileChange} />
                        </div>
                        <div className="form-group">
                            <button className="btn btn-primary" type="submit">Upload</button>
                        </div>
                    </form>
                </div>
            </div>
        )
    }
}

  • We declared the constructor and set the profileImg state and bind the events.

  • Inside the file input field, we passed the onChange event along with onSubmit method on the form.

  • 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.

This is image title

Conclusion

In this tutorial, we learned to upload a single file in React app and store the images in the MongoDB database using the Node server.

#react #node #javascript

What is GEEK

Buddha Community

How to upload a file in the React application with Node, Express and Multer
Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

I am Developer

1597559012

Multiple File Upload in Laravel 7, 6

in this post, i will show you easy steps for multiple file upload in laravel 7, 6.

As well as how to validate file type, size before uploading to database in laravel.

Laravel 7/6 Multiple File Upload

You can easily upload multiple file with validation in laravel application using the following steps:

  1. Download Laravel Fresh New Setup
  2. Setup Database Credentials
  3. Generate Migration & Model For File
  4. Make Route For File uploading
  5. Create File Controller & Methods
  6. Create Multiple File Blade View
  7. Run Development Server

https://www.tutsmake.com/laravel-6-multiple-file-upload-with-validation-example/

#laravel multiple file upload validation #multiple file upload in laravel 7 #multiple file upload in laravel 6 #upload multiple files laravel 7 #upload multiple files in laravel 6 #upload multiple files php laravel

Vincent Lab

Vincent Lab

1605177102

How to Upload Files to a Node.js Server

In this video, I’ll be showing you how to upload files to your Node.js server from a webpage.

#express #express-fileupload tutorial #multer file upload express example #how to upload files to node.js

I am Developer

1591071011

Laravel 7 File Upload Example

Here i will show you how to upload files in laravel 7, 6, 5 version. And simply upload file like pdf, image, xlx, zip etc in laravel app.

Laravel 7 file upload example

Checkout this laravel 7 file upload example:- https://www.tutsmake.com/laravel-6-file-upload-with-validation-tutorial/

#laravel file upload example #file upload in laravel 6 #file upload in laravel 7 #laravel file upload

Dvir Shabi

1572411558

How to upload a file in the React application with Node, Express and Multer

In this tutorial, we are going to learn how to upload a single file in React app. We will also learn to store image files in the MongoDB database using the Node server. Uploading image files is a day to day task of a web developer, if you are new to React, then this tutorial has the answer which you are looking for.

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

React Js 16+ File Upload with Node Server

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

Install React App

Enter the following command in your terminal and press enter.

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

Go to the project folder:

cd react-node-file-upload

Start your React app in the web browser:

npm start

View project on this URL: localhost:3000

Install Bootstrap 4 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

Head over to src > components directory and create a separate file by the name of files-upload-component.js.

import React, { Component } from 'react';

export default class 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-group">
                            <button className="btn btn-primary" type="submit">Upload</button>
                        </div>
                    </form>
                </div>
            </div>
        )
    }
}

Add 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';

class App extends Component {
  render() {
    return (
      <div className="App">
        <FilesUploadComponent />
      </div>
    );
  }
}

export default App;

This is image title

Create Node Server

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

Execute command 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 following node modules to build Node/Express server:

This is image title

Run command to install NPM packages:

npm install mongoose express cors body-parser uuid multer


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

Set up MongoDB

Create a backend > database folder and create a new file inside of it by the name of db.js.

module.exports = {
   db: 'mongodb://localhost:27017/react-fileupload-db'
};

Create Schema

Create a backend > models directory and create a fresh file inside of it and name it User.js.

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
    _id: mongoose.Schema.Types.ObjectId,
    profileImg: {
        type: String
    }
}, {
    collection: 'users'
})

module.exports = mongoose.model('User', userSchema)

We declared profileImg value with String data type along with Mongoose _id in Mongoose schema file.

Set up Express Routes

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

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

Run command from the root of the backend project.

mkdir public


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(null, DIR);
    },
    filename: (req, file, cb) => {
        const fileName = file.originalname.toLowerCase().split(' ').join('-');
        cb(null, uuidv4() + '-' + fileName)
    }
});

var upload = multer({
    storage: storage,
    fileFilter: (req, file, cb) => {
        if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") {
            cb(null, true);
        } else {
            cb(null, false);
            return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
        }
    }
});

// User model
let User = require('../models/User');

router.post('/user-profile', upload.single('profileImg'), (req, res, next) => {
    const url = req.protocol + '://' + req.get('host')
    const user = new User({
        _id: new mongoose.Types.ObjectId(),
        name: req.body.name,
        profileImg: url + '/public/' + req.file.filename
    });
    user.save().then(result => {
        res.status(201).json({
            message: "User registered successfully!",
            userCreated: {
                _id: result._id,
                profileImg: result.profileImg
            }
        })
    }).catch(err => {
        console.log(err),
            res.status(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;

Set up Server Js

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


let express = require('express'),
    mongoose = require('mongoose'),
    cors = require('cors'),
    bodyParser = require('body-parser'),
    dbConfig = require('./database/db');

const api = require('../backend/routes/user.routes')

// MongoDB Configuration
mongoose.Promise = global.Promise;
mongoose.connect(dbConfig.db, {
    useNewUrlParser: true
}).then(() => {
    console.log('Database sucessfully connected')
},
    error => {
        console.log('Database could not be connected: ' + error)
    }
)

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(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 `next()` method
    setImmediate(() => {
        next(new Error('Something went wrong'));
    });
});

app.use(function (err, req, res, next) {
    console.error(err.message);
    if (!err.statusCode) err.statusCode = 500;
    res.status(err.statusCode).send(err.message);
});

Test React File Upload API

In this step we will test REST API which we just created, before that we need to start the Node server. Follow the given below process to start the Node/Express server.

Run command to start the mongoDB.

mongod

Run nodemon server by executing the following command:

nodemon server

This is image title

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

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

This is image title

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 code in src/components/files-upload.component.js file.


import React, { Component } from 'react';
import axios from 'axios';

export default class 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: e.target.files[0] })
    }

    onSubmit(e) {
        e.preventDefault()
        const formData = new FormData()
        formData.append('profileImg', this.state.profileImg)
        axios.post("http://localhost:4000/api/user-profile", formData, {
        }).then(res => {
            console.log(res)
        })
    }


    render() {
        return (
            <div className="container">
                <div className="row">
                    <form onSubmit={this.onSubmit}>
                        <div className="form-group">
                            <input type="file" onChange={this.onFileChange} />
                        </div>
                        <div className="form-group">
                            <button className="btn btn-primary" type="submit">Upload</button>
                        </div>
                    </form>
                </div>
            </div>
        )
    }
}

  • We declared the constructor and set the profileImg state and bind the events.

  • Inside the file input field, we passed the onChange event along with onSubmit method on the form.

  • 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.

This is image title

Conclusion

In this tutorial, we learned to upload a single file in React app and store the images in the MongoDB database using the Node server.

#react #node #javascript