Receiving Uint8Array on Node.js and Saving on Google Cloud Storage

Flutter → Node.js → Google Cloud Storage

Although I’ve written a similar post about sending an image from Flutter to Node.js server to Google Cloud Storage and vice-versa, I’ve found that it didn’t work when I ran the app on my phone (while it did work on my iOS and Android emulators). So, this will be a super short post on receiving Uint8Array on Node.js to send to Google Cloud Storage.

Flutter

On my app, when the user selects a photo or multiple photos, I save it accordingly to my Photo class, which is composed of (String) fileName and (Uint8List) bytes. (1) Bytes — you can get it by await xFile.readAsBytes() (XFile is the format you get your image in when you use image_picker). (2) FileName — I just get the last bit of the full path of the image using .split(“/”).last.

Photo Service

In my Photo class, I have a factory constructor to convert my data from JSON to Photo, a method to convert the Photo to JSON, and a static method to convert a List<Photo> to List<JSON format>. In my POST request, I attach the returned value from photoListToJson() to the body[“photos”].

Photo Class

Node.js

My Node.js is divided into index.js, routers, and controllers. In index.js, I’ve found that you need the below Express middleware, or you’ll get “request entity is too large” error.

app.use(express.json({ limit: "50mb" }));
photos router

In my previous post, I used bucket.upload() but after some googling, I’ve switched to file.save(), which takes a Buffer as an argument. (1) When you receive the bytes array, create an instance of Uint8Array, which is extended by the Buffer class. (2) Use bucket.file(filename) to create a File object. (3) await file.save(Uint8Array) to upload.

Note: my server receives a List of Photo data, which is why I had to use Promise().

Done! If you need to know how to get the images from cloud storage and send it to Flutter, please refer to my previous post.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store