+ Start a Discussion

Read the attachment body from an apex class


I am trying to read the content of an attachment from an apex class. 

 Attachment att=   [Select Id,a.ParentId, a.Name,a.body,a.ContentType From Attachment a where ParentId=:contactId limit 1];
           System.debug('Attachment body : '+ att.body);
        System.debug('Attachment body : '+ att.ContentType);

 the attachment body  content is displayed as :Blob[176680].
the body of the attachment is base64. I want to see the content of the body in plain english .

Any help is appreciated.


You have to use att.body.toString() to get the content of the attachment. This only works if the blob is actually contains only text and not binary data.

When I use att.body.toString() , I get the error Blob is not a valid UTF-8 .Instead I have used EncodingUtil.base64Encode(att.body). Now I am not getting an error. But the string is not in readable form.


att.body is a base64 encoded. Any help to convert the body to readable form is appreciated.




As I said, if you can't read it using Blob.toString(), you won't be able to read it easily. For example, you can read a .txt file, but not a .docx file. You can read a .rtf file, but not a .gif file.