function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

How to store an Attachment with a JPEG file from HttpRequest.

Hi All,


I want to store a JPEG file in an Attachment object. The source of this JPEG file is an HttpRequest Object. Here's my code:



Http http = new Http();

HttpRequest httpRequest = new HttpRequest();

httpRequest.setEndPoint(''); //jpeg file to retrieve!


httpRequest.setHeader('Content-Type', 'image/jpeg');

string responseBody = http.send(httpRequest).getBody();



Attachment a = new Attachment();

Blob b = Blob.valueOf(responseBody);

a.body = b;

a.ParentId = '0038000000l4H5hAAE'; //a ContactId

a.contentType = 'image/jpeg'; = 'Hildegunn';

insert a;


First of all, I create an HTTPRequest object pointinf to the URL of the JPEG file I want to grab, set method (GET) and content type. Then I submit the request and store body's response (THE JPEG FILE!). If I debug the responseBody variable, I get the ASCII content of the image file. So, the file is correctly retrieved.


The next part of the code, I create an Attachment object, link with corresponding ParentId, create Blob from responseBody and set Attachment's body.


Everything looks ok, I go to Contact's attachments and see the brand new attachment, BUT when i click VIEW attachment link, i get the following response: 



Looking the response in more detail, I have the following HTML:





<img src=";otk=DrIT7n0CrBzY0Aw.rwJj61MiYURrs732h1pr1rj4l3FbqKulnu0pr5xq1.yoY_04&amp;retURL=%2F0038000000l4H5hAAE&amp;rtype=D"

alt=";otk=DrIT7n0CrBzY0Aw.rwJj61MiYURrs732h1pr1rj4l3FbqKulnu0pr5xq1.yoY_04&amp;retURL=%2F0038000000l4H5hAAE&amp;rtype=D"/> </body>



As you can see, the img tag is not able to retrieve the file, so is displaying the ALT attribute.


Any ideas?





Message Edited by Aldof on 10-06-2009 10:20 AM

I found a link that knows how to do this...


In the recent Spring release (v24) ... you can now work with binary data (blobs in apex) directly in the http request or response. Here's an example of making a HTTP GET request for an image PNG file, and saving it to the document object in salesforce.


Here is the code in that link:


HttpRequest r = new HttpRequest();
Http http = new Http();
HttpResponse res = http.send(r);
blob image = res.getBodyAsBlob();

Document d = new Document(); = 'logo.png';
d.body = image;
d.folderId = UserInfo.getUserId();
insert d;