The open blogging platform. Say no to algorithms and paywalls.

Upload Files to Google Cloud Storage from React

A tutorial on how to upload files to Google Cloud Storage from React using Node.js and Multer

Photo by Aideal Hwa on Unsplash

Today we will see how we can upload files to Google Cloud Storage using Node.js backend from the React front-end.

Step 1: Do the front-end

The front-end code is very easy. We will just need a file picker to select a file from our local machine and send it to our Node.js server.

Prepare the cloud storage:

Go to your Google Cloud console and create a service account that has permission to upload files to Google Cloud Storage.

Then download the key file for that service account and store it inside a secure place.

Then head over to the Cloud storage option in your cloud console and create a bucket.

We are not showing that part here to avoid making this article too long.

Prepare the backend

Let's first initialize the project by installing some dependencies.

yarn add @google-cloud/storage express cors multer

Here multer is a special middleware for Express that helps with file uploads.

@google-cloud/storage is our client for uploading a file to Google Cloud Storage.

Then create our server using the following code:

  1. Here we are creating our Express application.

  2. Then we are creating a multer instance.

  3. Then configuring our cloud storage client by providing a path to the cloud storage client

    import { Storage } from "@google-cloud/storage"; import express from "express"; import cors from "cors"; import { format } from "util"; import Multer from "multer"; const app = express(); const port = 5000;

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

    app.use(cors());

    const cloudStorage = new Storage({ keyFilename: ${__dirname}/service_account_key.json, projectId: "PROJECT_ID", }); const bucketName = "YOUR_BUCKET_NAME";

    const bucket = cloudStorage.bucket(bucketName);

    app.post("/upload-file-to-cloud-storage", multer.single("file"), function (req, res, next) { if (!req.file) { res.status(400).send("No file uploaded."); return; }

    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/${bucket.name}/${blob.name});

    res.status(200).json({ publicUrl });
    

    });

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

    app.listen(port, () => { console.log(listening at http://localhost:${port}); });

Then start the server using the following command:

node index.js

Keep the server running and try to upload a file using our React front-end.

Download file

You can also download the files from the cloud storage using this same client library. Use the following function to generate a signed download URL that allows you to securely access the file.

app.get("/get-url", (req, res) => {
  const file = bucket.file("FILE_NAME_IN_THE_BUCKET");
  const config: any = {
    action: "read", // giving read permission here
    expires: "03-17-2025", // specifying the expiry date
  };
  file.getSignedUrl(config, (err, url) => {
    res.status(200).json({ url });
  });
});

List the files

To get a list of the files from the cloud storage, you can use the following code:

app.get("/get-files-list", async (req, res) => {
  const options = {
    prefix: "audio", // or anything you want!
  };
  const [files] = await bucket.getFiles(options);
  res.status(200).json({ files });
});

So this is a super short tutorial to show you how to upload files to google cloud storage. Hope you learned something new today!

Have a great day!

Get in touch with me via LinkedIn or my Personal Website.

Upload Files to Google Drive from React without OAuth2




Continue Learning