javagoogle-cloud-storagemandrillgcloud-java

Image or Pdf File download from Gcloud Storage is corrupted


I am using file downloaded from Gcloud storage as attachment to Mandrill API for sending as an attachment in email. The problem is it's only working for Text file, but for Image or Pdf, the attachment is corrupted. Following Code is for downloading the file and converting it to Base64 encoded String.

Storage.Objects.Get getObject = getService().objects().get(bucket, object);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    // If you're not in AppEngine, download the whole thing in one request, if possible.
    getObject.getMediaHttpDownloader().setDirectDownloadEnabled(true);
    getObject.executeMediaAndDownloadTo(out);
    //log.info("Output: {}", out.toString("UTF-8"));
    return Base64.encodeBase64URLSafeString(out.toString("UTF-8")
        .getBytes(StandardCharsets.UTF_8));

I am setting this String in Content of MessageContent of Mandrill API.


Solution

  • Got it working. I only needed to store the OutputStream in a temp File before using it as attachment in email. Posting the code below for reference.

    Storage.Objects.Get getObject = storage.objects().get("bucket", "object");
    
    OutputStream out = new FileOutputStream("/tmp/object");
    // If you're not in AppEngine, download the whole thing in one request, if possible.
    getObject.getMediaHttpDownloader().setDirectDownloadEnabled(true);
    getObject.executeMediaAndDownloadTo(out);