Reactjs file upload to google cloud storage using multer, express and nodejs.

0
Reactjs Google cloud storage file upload

If you want to know how to upload files directly to google cloud storage using Reactjs, then you are at right place. In this tutorial, we have covered reactjs file upload directly to google cloud storage using multer, express, nodejs. I have used react-dropzone-component to upload the file from Reactjs. It has a good amount of configuration and features with UI(filepicker.css). Our server is in nodejs with express and I have used multer npm module to get rid of file uploading process directly to google cloud storage. Might be you haven’t heard about Google cloud storage but you definitely heard about AWS S3. Google cloud is as same as Amazons S3 bucket. So we will proceed with google cloud storage file upload using reactjs.

Software stack used for Reactjs file upload to google cloud storage:
1. ReactJs: for frontend development. React tutorial
2. ExpressJs: for API development.
3. Nodejs: for server-side development.
4. @google-cloud/storage SDK: to interact with Google cloud storage.
5. Multer: as middleware to upload the files.
6. react-dropzone-component: Reactjs component to upload the files with drag and drop.

 

react-file-upload

Let’s get started with file reactjs file upload component with react-dropzone-component:

First of all, I have started by cloning reactjs seed app from GitHub for a basic react app. After setting up basic app we are ready to go for further. In this example, we have used React-Dropzone-Component for drag and drop file upload functionality. To utilize the features of react-dropzone-component, we need to install it first as below.

npm install react-dropzone-component --save

After react-dropzone-component getting installed import it to use in our app.

import DropzoneComponent from 'react-dropzone-component';

There is some configuration which is provided by the react dropzone component module. This configuration is done as shown below. It includes file types, post url to upload file etc.

const djsConfig = {
    addRemoveLinks: true,
    acceptedFiles: "image/jpeg,image/png,image/gif"
};

const componentConfig = {
    iconFiletypes: ['.jpg', '.png', '.gif'],
    showFiletypeIcon: true,
    postUrl: '/uploadHandler'   // route url to upload file over server
};

react-dropzone-component provides events such as addedfile, success, removefile, uploadprogress etc. This events can be setup as shown below

const eventHandlers = {
    init: dz => this.dropzone = dz,
    drop: this.callbackArray,
    addedfile: this.callback,
    success: this.success,
    removedfile: this.removedfile,
    uploadprogress: this.progress
}

Now its time to define react-dropzone-component as below:

<DropzoneComponent config={config} eventHandlers={eventHandlers} djsConfig={djsConfig} />

As a result, our upload file component will look like this:

DefaultUpload.js
import React from 'react';
import ReactDOM from 'react-dom';
import DropzoneComponent from 'react-dropzone-component';

export default class DefaultUpload extends React.Component {
    constructor(props) {
        super(props);

        this.djsConfig = {
            addRemoveLinks: true,
            acceptedFiles: "image/jpeg,image/png,image/gif"
        };

        this.componentConfig = {
            iconFiletypes: ['.jpg', '.png', '.gif'],
            showFiletypeIcon: true,
            postUrl: '/uploadHandler'
        };

        // If you want to attach multiple callbacks, simply
        // create an array filled with all your callbacks.
        this.callbackArray = [() => console.log('Hi!'), () => console.log('Ho!')];

        // Simple callbacks work too, of course
        this.callback = () => console.log('Hello!');

        this.success = file => console.log('uploaded', file);

        this.progress = file => console.log('progress', file);

        this.removedfile = file => console.log('removing...', file);

        this.dropzone = null;
    }

    render() {
        const config = this.componentConfig;
        const djsConfig = this.djsConfig;

        // For a list of all possible events (there are many), see README.md!
        const eventHandlers = {
            init: dz => this.dropzone = dz,
            drop: this.callbackArray,
            addedfile: this.callback,
            success: this.success,
            removedfile: this.removedfile,
            uploadprogress: this.progress
        }

        return <DropzoneComponent config={config} eventHandlers={eventHandlers} djsConfig={djsConfig} />
    }
}

Import file upload component in app.js file.

import React from 'react';
import ReactDOM from 'react-dom';
import DefaultUpload from './DefaultUpload';

class FileUpload extends React.Component {
    render() {
        return (
            <div className="example">
                <h2>
                    React Js File upload to google cloud storage using multer
                </h2>
                <p>This is the default use, posting to the google cloud storage.</p>
                <DefaultUpload />
            </div>
        );
    }
}

ReactDOM.render(<FileUpload />, document.getElementById('app'));

That’s it from our frontend using Reactjs. We have design file upload component with the help of DropzoneComponent.

Server-side code to upload the files to google cloud storage using multer.

Let’s move towards server-side functionality using multer, express and nodejs. Below is our server.js file and the code is very much self-explanatory with comments.

server.js
const format = require('util').format;
const express = require('express');
const Multer = require('multer');
const helmet = require('helmet');
const path = require('path');
const bodyParser = require('body-parser');
const Storage = require('@google-cloud/storage');   // google cloud sdk
const storage = Storage();
const app = express();

app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, '')));

const multer = Multer({
  storage: Multer.memoryStorage(),
  limits: {
    fileSize: 5 * 1024 * 1024 // no larger than 5mb, you can change as needed.
  }
});

// Signup for google cloud storage and get bucket name
var bucketname = <googel_cloud_storage_bucket_name>;

// A bucket is a container for objects (files).
const bucket = storage.bucket(bucketname);

// Process the file upload and upload to Google Cloud Storage.
app.post('/uploadHandler', multer.single('file'), (req, res, next) => {
  if (!req.file) {
    res.status(400).send('No file uploaded.');
    return;
  }

  // Create a new blob in the bucket and upload the file data.
  const blob = bucket.file(req.file.originalname);
  const blobStream = blob.createWriteStream();

  blobStream.on('error', (err) => {
    next(err);
  });

  blobStream.on('finish', () => {
    // The public URL can be used to directly access the file via HTTP.
    const publicUrl = format(`https://storage.googleapis.com/${bucketname}/${blob.name}`);
    res.status(200).send(publicUrl);
  });

  blobStream.end(req.file.buffer);
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`App listening on port ${PORT}`);
  console.log('Press Ctrl+C to quit.');
});

Conclusion:

Finally, we are at the conclusion that, we have just implemented file upload functionality using reactjs, multer, express and nodejs with the help of awesome react component DropzoneComponent.

GitHub source code

LEAVE A REPLY

Please enter your comment!
Please enter your name here