1

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.

Zachary Newman
  • 20,014
  • 4
  • 39
  • 37
pradex
  • 328
  • 4
  • 18
  • Since MessageContent.Content expects a String, not a byte array, I assume you are passing base64.encodeBase64URLSafeString(out.toString("UTF-8")) as MessageContent but only using getBytes() here to test the corruption? – Adam Feb 16 '16 at 00:58
  • Yes that is the reason why i am using base64.encodeBase64URLSafeString but i have also tried Base64.encodeBase64URLSafeString(out.toByteArray()) which yields the same result. Only text files are coming properly rest are corrupted. – pradex Feb 16 '16 at 09:28
  • 1
    I reckon the problem is with downloading complete data at once. Because with more testing i see that big text files are also not fetching all data as some parts are corrupted. – pradex Feb 16 '16 at 15:54

1 Answers1

0

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);
pradex
  • 328
  • 4
  • 18