Download and Upload Images In Google Cloud Storage

Hey guys, recently I was working on a application where I need to upload the images in google Cloud storage, I searched a lot and started banging my head on the wall because there was so many tutorial out there and none was fitting into my use case.
My usecase was, my client application (which is mobile developed in react-native) sending me image base64 string and json data together, when I searched on stackoverflow and GCS docs all were using either multipart or some other annotation, but those were not useful for me as my usecase was..( as mentioned above).
So after spending a day I wrote some code which is working for me.
I am posting here a sample code for uploading and download Images (basically base64) from and to Google Cloud storage,
I have a SpringBoot Application deployed on Google App Engine.
My Client Side application is written in React-Native
Client is sending me some Data and Image base64 string in one single json object like below

{
    "code":"BA001",
    "date":"24-04-1992",
    "mobile":"9202209519",
    "remarks":"remarks",
    "reminderDate":"12-04-2016",
    "amount":"5000",
    "document":"base64 Image"
}
 In My document element I am getting an Image (which is base64 String) which is coming in string format.

Here is my controller

@RequestMapping(value="/saveLeadDetails",method=RequestMethod.POST)
    public @ResponseBody ResponseSchema saveDetails(@RequestBody RequestSchema request) {
        ResponseSchema response = service.saveDetails(request);
        return response;
    }
In my pojo class the document element is declared as String

@JsonProperty("document")
private String document;


@JsonProperty("document")
public String getDocument() {
return document;
}

@JsonProperty("document")
public void setDocument(String document) {
this.document = document;
}

Now here comes the main part

@Override
    public ResponseSchema saveLeadDetails(RequestSchema request) {
        ResponseSchema response = new ResponseSchema();
        try {
            String id= UploadDocuments(request);
            String data = downloadObject();
            Generationdb req = new Generationdb();
            req.setAmount(request.getAmount());
            req.setBranchCode(request.getBranchCode());
            req.setInterestedIn(request.getInterestedIn());
            req.setMobile(request.getMobile());
            req.setName(request.getName());
            req.setProduct(request.getProduct());
            req.setRemarks(request.getRemarks());
            req.setReminderDate(request.getReminderDate());
            req.setDocument(id);
            leadGenerationRepository.save(req);
            response.setStatus(data);
            response.setResponseCode(ApplicationConstant.SUCCESS_CODE);
            response.setResponseMessage(ApplicationConstant.SUCCESS_MESSAGE);
          
        }catch(Exception e){
            response.setResponseCode(ApplicationConstant.ERROR_CODE);
            response.setResponseMessage(ApplicationConstant.FAILURE_MESSAGE);
            response.setErrorMessage("ERROR001-"+e.getMessage());
        }
        return response;
    }

This code is used to upload the Image in google Cloud Storage which will take base64 String and it will decode the Base64 string and will upload it into your bucket.
private String UploadDocuments(RequestSchema request) {
       final String fileName = "myImage"; 
try {
        String bucketName = "documents";
        Date date= new Date();
        long time = date.getTime();
       // InputStream ipstream = convertMultiPartToFile( request.getDocument() );
        Credentials credentials = GoogleCredentials.fromStream(MyClass.class.getClassLoader().getResourceAsStream("gcs-ba943a4c3871.json")); // use this if .json file is in your project resource folder
       // Credentials credentials = GoogleCredentials.fromStream(new FileInputStream("/Users/username/Desktop/gcs-ba943a4c3871.json")); // use this if .json file is outside project (In my case its desktop)
        Storage storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();
        BlobId blobId = BlobId.of(bucketName, fileName);
        BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
        Blob blob = storage.create(blobInfo, Base64.decodeBase64(request.getDocument().getBytes()));
        }catch(Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }
    This code us used te get the base64 string from your gcs bucket, it will get the content in byte[] and encode it in base64
    private String downloadObject() {
        String PROJECT_ID = "project-id";
        String BUCKET_NAME = "documents";
        String OBJECT_NAME = "myImage";
        StorageOptions options = null;
        try {
            options = StorageOptions.newBuilder()
                    .setProjectId(PROJECT_ID)              .setCredentials(GoogleCredentials.fromStream(FinomaticServiceImpl.class.getClassLoader().getResourceAsStream("gcs-ba943a4c3871.json"))).build();ba943a4c3871.json"))).build();
        } catch (IOException e) {
            e.printStackTrace();
        }

    Storage storage = options.getService();
    Blob blob = storage.get(BUCKET_NAME, OBJECT_NAME);
    byte[] content = blob.getContent(BlobSourceOption.generationMatch());
    String s = new String(content);
    byte[] encodedBytes = Base64.encodeBase64(content);
    return new String(encodedBytes);
    }

so now everything is done,
feel free to contact in case of any issue.

email - behappiest1992@gmail.com

Happy Coding 🙏