使用sendgrid-JAVA的PDF附件

时间:2018-02-23 06:32:26

标签: java pdf email-attachments sendgrid

添加内容的代码:

for (Attachment attachment:message.getSendGridAttachments()) {
   nvps.add(new BasicNameValuePair(String.format(PARAM_FILES, attachment.getName()),attachment.getData()));
}

在附件类中:

public class Attachment implements Serializable{

    public  String name;
    public  InputStream contents;
    public  String data;
    public  String type;
    public String getType() {
        return type;
    }
    public String getData() {
        return data;
    }

    public String getName() {
        return name;
    }

    public InputStream getContents() {
        return contents;
    }

    public Attachment(File file) throws FileNotFoundException {
        byte[] fileData = null;
        try {
            fileData = org.apache.commons.io.IOUtils.toByteArray(new FileInputStream(file));
        } catch (IOException ex) {

        }
        try {
            this.data = new String(fileData, 0, (int) file.length(), "UTF-8");
            LOG.info("data is :{}",new String(fileData, 0, (int) file.length(), "UTF-8") );
        } catch (UnsupportedEncodingException e) {
        }
        this.name = file.getName();
        this.contents = new FileInputStream(file);
        this.type = "application/pdf";
    }

    public Attachment(String name, InputStream contents, String data) {
      this.name = name;
      this.contents = contents;
      this.data = data;
    }

}

这里的问题是我在附件中获得了10kb的pdf文件,但在打开时却没有显示任何内容。

当我使用文本编辑器打开同一个文件时,它会向我显示一些垃圾数据(看起来像字节流)

1 个答案:

答案 0 :(得分:0)

您正在阅读文件内容两次;你不能做这样的事情:

public class Attachment implements Serializable{

    public  String name;
    public  byte[] data;
    public  String type;
    public String getType() {
        return type;
    }
    public String getData() {
        try {
            return new String(data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // very unlikely
        }
    }

    public String getName() {
        return name;
    }

    public InputStream getContents() {
        return new ByteArrayInputStream(data);
    }

    public Attachment(File file) throws FileNotFoundException {
        try {
            data = org.apache.commons.io.IOUtils.toByteArray(new FileInputStream(file));
        } catch (IOException ex) {

        }
        this.name = file.getName();
        this.type = "application/pdf";
    }

    public Attachment(String name, byte[] data, String type) {
      this.name = name;
      this.data = data;
      this.type = type;
    }

}