Play Games

Search This Blog

Wednesday, October 28, 2015

Insert Image as Attachment in Salesforce

If you have the image url and if you want to insert that image as attachment to any object,
then you need to do get request and then insert attachment with the content of response data.

Apex class :
public class InsertImageAsAttachment{
    public void insertImage() {
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://upload.wikimedia.org/wikipedia/commons/thumb/d/da/Purple_flower_%284764445139%29.jpg/581px-Purple_flower_%284764445139%29.jpg');
        req.setMethod('GET');
        Http http = new Http();
        HTTPResponse res = http.send(req);
        blob picture = res.getBodyAsBlob();
        Attachment attachObj = new Attachment (ParentId = '00128000003yhTi',Body = picture,Name = 'flower.jpg');
        insert attachObj;
   }
}

In this example,I have taken one image in google whose url is "https://upload.wikimedia.org/wikipedia/commons/thumb/d/da/Purple_flower_%284764445139%29.jpg/581px-Purple_flower_%284764445139%29.jpg".
ParentId will be the id of object to which you need to attach image as attachment.

When you call insertImage() ,the image will get inserted as attachment.
Output:




Note: 1)You need to add the endpoint url in remote site settings.
          2)The endpoint url will be the url of image.
          3) If the image is in any external system which needs authentication,then you need
              to do authentication as well.