How to load an attachment in a browser?

I use the Gmail API in a browser and want to allow the user to download email attachments. I see https://developers.google.com/gmail/api/v1/reference/users/messages/attachments/get , but it returns JSON and base64 data. I don’t think I can get this data in memory, and then run the “download” to save the file locally. Even if I could not think that it would be effective - perhaps it will load the file into memory and stream it to a file. I think I need a direct link to a file that returns the correct file name and raw binary data (and not base64). Is there any way to do this? Right now, I see only proxy requests.

+4
source share
1 answer

You can get the data from base64 and save it to a file locally.

If you get an attachment in Java, you can use the FileOutputStreamclass (or f.write() in Python)to write bytes to a file and save it locally using the path.

You can try with the following code example on the Google developer page:

public static void getAttachments(Gmail service, String userId, String messageId)
      throws IOException {
    Message message = service.users().messages().get(userId, messageId).execute();
    List<MessagePart> parts = message.getPayload().getParts();
    for (MessagePart part : parts) {
      if (part.getFilename() != null && part.getFilename().length() > 0) {
        String filename = part.getFilename();
        String attId = part.getBody().getAttachmentId();
        MessagePartBody attachPart = service.users().messages().attachment().
            get(userId, messageId, attId).execute();
        byte[] fileByteArray = Base64.decodeBase64(attachPart.getData());
        FileOutputStream fileOutFile =
            new FileOutputStream("directory_to_store_attachments" + filename);
        fileOutFile.write(fileByteArray);
        fileOutFile.close();
      }
    }
  }
0
source

All Articles