0
votes

Code to add content:

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

In Attachment Class:

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;
    }

}

Problem here is I am getting 10kb pdf file in attachment but while opening its showing nothing.

When I open same file using text editor it shows me some garbage data(seems like byte stream)

1

1 Answers

0
votes

You're reading the file contents twice; couldn't you do something like this:

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;
    }

}