Upload Images to Google Cloud Storage with React Native and ExpressJS
With ~12 hours of investigation and eventual success, I feel the need to save some grief for anyone approaching this same challenge.
Google Cloud Storage is Google’s version of Amazon S3 Buckets. I use Google Cloud because the dashboard is really nice to navigate, it‘s directly connected with Google’s API’s , and services are easy to configure and start up.
Here is the section of Google Cloud’s docs that I followed.
In my particular case, I was uploading the images from a React Native app via the react-native-image-picker, to an endpoint on my express server, and then on to Google Cloud.
The Items needed for a successful upload:
The Steps needed for a successful upload
- Accept the image via Image Picker/Form, or any other file selector.
- Creating a
- Appending the image details to the Object
- Performing a
POSTrequest to your Express endpoint as
multeras middleware to parse the request and add a
fileproperty to the
- Middleware service to 1) Authenticate with the Google API, 2) define the storage bucket, 3) specify the file name, 4) Upload the image, and 5) send the response
- Passing the above service as middleware to your route, uploading the file and returning the final Image URL.
Getting Your Google Cloud Service Account Keyfile
In your Google Cloud console (console.cloud.google.com), go to the API Manager.
- Ensure the Google Cloud Storage JSON API is enabled.
- Go to Credentials > Create Credentials > Service Account Key
- Under service account, select create a new service account
- Once that is created, then you can generate the JSON keyfile.
- Save that keyfile to your Express project directory.
Accepting the Image as User Input
You can do this with standard HTML by defining the
enctype=multipart/form-data and setting the image picker as
<input type="file"> and you’ll be able to achieve the same result.
In my case, here’s what the handled input looked like:
The key points here being the
FormData() object construction, and the
POST Request for Image Upload on the Server
npm install --save @google-cloud/storage multerinside of your express directory to install the storage segment of the Google Cloud Node library.
Accept the image from the front-end request below:
The Image Uploading Middleware: Where you’ll use that service account keyfile that was generated in the first step.
From the route, an object is returned:
And that URL can be accessed directly in the browser, serving up the image publicly for use within your application.
Thanks for reading! I hope this helped you to continue on your journey to creating something awesome.
This knowledge from this post was discovered during the creation of Date Hatcher, an activity based dating app designed for going on real dates. Coming soon to an app store near you.