I am trying to get an image located at https://na1.salesforce.com/servlet/servlet.FileDownload?file=00P24000002sSRUEA2 in an apex controller and it complains about authorization..Below is my code

HttpRequest req = new HttpRequest(); req. req.setEndpoint('https://na1.salesforce.com/servlet/servlet.FileDownload?file=00P24000002sSRUEA2'); 
 Http binding = new Http(); 
HttpResponse res = binding.send(req); 
Blob image = res.getBodyAsBlob(); 
System.debug('image' + EncodingUtil.base64Encode(image));

i am new to apex.how do i do this right

  • Is this the same instance you are working where the image is available? or some other SF instance? Commented Dec 3, 2015 at 12:37
  • yes.the image is in the same instance
    – Kojo Davis
    Commented Dec 3, 2015 at 15:06

2 Answers 2


if your image is in same org then just query the attachment record and use the body.

attachment acc = [select id,body from attachment where id = '00P24000002sSRUEA2' LIMIT 1] //id hardcode is not a good option you have to be double sure that you need this or store this in custom setting

then use

String strImage = 'data:image/png;base64,'+EncodingUtil.base64Encode(acc.body);  

but if this is a single image or you need to display it somewhere else then store this in Static Resource, make it public and use the static resource.

  • thanks man..this helped.but can you get me some resources on how make it a static public resource since it will be only a single imag..thanks again
    – Kojo Davis
    Commented Dec 3, 2015 at 17:37

What's the error message?

If the image lives in another org to the one you're in, you might be getting hit with a CORS (cross origin resource sharing) error.

  • when i try to access the base64 encoded image it redirects me to a salesforce login page.NB image is in the same org. Also this image needs to be shown a android mobile client
    – Kojo Davis
    Commented Dec 3, 2015 at 12:07
  • odd. It shouldn't need to re-authenticate. Where does teh image live? Is it an attachement somewhere, a chatter image, in Files, in Documents? I'm wondering if there are some privacy setting on the image file stopping you
    – smatharu
    Commented Dec 4, 2015 at 9:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .