Upload files to Google Cloud Storage from React
With the help of NodeJS and Multer
Today we will see how we can upload files to Google Cloud Storage using NodeJS backend from the ReactJS 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 nodejs server.
import React, { useState } from "react";
function GoogleStorageFileUploader() {
const [url, setUrl] = useState("");
const [file, setFile] = useState < any > null;
const handleSubmit = async (e: any) => {
e.preventDefault();
let formData = new FormData();
formData.append("file", file.data);
const response = await fetch("http://localhost:5001/upload-file-to-cloud-storage", {
method: "POST",
body: formData,
});
const responseWithBody = await response.json();
if (response) setUrl(responseWithBody.publicUrl);
};
const handleFileChange = (e: any) => {
const img = {
preview: URL.createObjectURL(e.target.files[0]),
data: e.target.files[0],
};
setFile(img);
};
return (
<form onSubmit={handleSubmit}>
<input type="file" name="file" onChange={handleFileChange}></input>
<button type="submit">Submit</button>
</form>
);
}
export default GoogleStorageFileUploader;
Prepare the cloud storage:
Go to your google cloud console and create a service account that has permission to upload files to the 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, making this article too large.
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 the 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.
- Here we are creating our express application
- Then create a multer instance
- 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}`);
});
And 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!