2014-03-30 73 views
2

我正在嘗試使用Mandrill Wrapper for Java在電子郵件中附加文件。這是我正在處理附件文件的一段代碼。Mandrill/Java - 連接文件損壞

public byte[] attachmentContent(String filepath) 
{ 
    Path path = Paths.get(filepath); 
    byte[] data = null; 
    try { 
     data = Files.readAllBytes(path); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return data; 
} 

    //adding attachment 
    ArrayList<MandrillAttachment> attachedFiles = new ArrayList<MandrillAttachment>(); 
    //file 1 
    String attType = "application/pdf"; 
    String attName = "Indian License.pdf"; 
    String attContent = Base64.encodeBase64URLSafeString(attachmentContent("C:\\LL Indian License.pdf")); 
    System.out.println(attContent); 
    //attach 
    attachedFiles.add(new MandrillAttachment(attType, attName, attContent)); 
    message.setAttachments(attachedFiles); 

但是,該文件通過發送進程損壞。任何想法如何解決這個問題?

+0

您如何知道文件已損壞?你能舉個例子嗎? – klarki

+0

我正在使用一個炒作pdf文件(這意味着,我可以打開並閱讀它)。但是,在我通過電子郵件發送後,使用我寫的代碼,我無法打開PDF文件。當我嘗試打開時,它說文件「損壞」 – aeros

+0

是的,但它看起來如何?也許它與base64兩次編碼...你可以發佈一個片段? – klarki

回答

1

(這可能來不及回答)使用適當的Base64編碼來避免此問題。我使用下面的代碼來解決這個問題。

import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.util.ArrayList; 
import java.util.List; 
import org.apache.commons.codec.binary.Base64; 

List<MessageContent> listofAttachments = new ArrayList<MessageContent>(); 
    MessageContent attachment = new MessageContent(); 
    attachment.setType("application/pdf"); 
    attachment.setName("Test.pdf"); 

    File file = new File("C:\\Users\\xxx\\PdfTesting\\Test.pdf"); 

    InputStream is = new FileInputStream(file); 

    long length = file.length(); 
    if (length > Integer.MAX_VALUE) { 
     // File is too large 
    } 
    byte[] bytes = new byte[(int) length]; 

    int offset = 0; 
    int numRead = 0; 
    while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) { 
     offset += numRead; 
    } 

    if (offset < bytes.length) { 
     throw new IOException("Could not completely read file " + file.getName()); 
    } 

    is.close(); 
    byte[] encoded = Base64.encodeBase64(bytes); 
    String encodedString = new String(encoded); 
    attachment.setContent(encodedString); 
+0

嗯,我無法解決類MessageContent。它從何而來?找不到任何地方。 – pidabrow

+0

MessageContent是Mandrill庫中的一個類。 – Jeeri