2014-11-24 29 views
4

我在瀏覽器中使用Gmail API,並希望允許用戶下載電子郵件附件。我看到https://developers.google.com/gmail/api/v1/reference/users/messages/attachments/get,但它返回JSON和base64數據。我不認爲我可以在內存中獲取該數據,然後觸發「下載」以在本地保存文件。即使我可以,我不認爲它會有效 - 它可能會下載內存中的文件或將其流式傳輸到文件。我想我需要一個直接鏈接到一個文件,該文件返回正確的文件名和原始二進制數據(不是base64)。有沒有辦法做到這一點?現在我看到的唯一方法是代理請求。如何在瀏覽器中下載附件?

回答

0

您可以從base64獲取數據並將其保存到本地文件。

如果您使用Java獲取附件,則可以使用FileOutputStream(or f.write() in Python)將字節寫入文件並使用路徑在本地保存。

您可以用谷歌開發者頁面下面的示例代碼嘗試:

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

我在瀏覽器客戶端談論所以必須能夠與瀏覽器限制,這樣做在JavaScript。 – dgobaud 2014-11-26 00:20:34

相關問題