3

I have tried this codes but the image is still not being save into the file in the Document Folder.

Can anyone help me fix my code so that it can save an image?


Apex Class

public void send(){

    String image1 = 'https://ap4.salesforce.com/servlet/servlet.ChartServer?rsid=0FL6F000002dBX3&ruid=0056F00000746E0&did=01Z6F000001DwLb&s=7&fs=10&tfg=12&tfs=-16772063&explode=0&c=gauge&cs=0&title=Closed+Sales+To+Date&eh=no&compo=no&fg=-16777216&bg1=-1&bg2=-1355393&bgdir=2&dl1=Account+Name&dl2=&l=2&sax=yes&Yman=no&nc=0&actUrl=%2F00O2F00000Aug7k%3Fdbw%3D1&sd=1&scv=no&sct=yes&spt=no&bd=yes&cu=SGD&ab=X&u=0&vt=0&ab2=Y&u2=1&vt2=2&vl0=Sum+of+Amount&spoc=no&topn=no&gm=0.0&gc0=-6750208&gm0=500000.0&gc1=-13210&gm1=1000000.0&gc2=-16738328&gm2=1500000.0&sona=0&refreshts=1491552381000';


    String base64Data = '';
    HttpRequest req = new HttpRequest();
    req.setEndpoint(image1);
    req.setMethod('GET');
    Http http = new Http();
    HttpResponse res = http.send(req);
    Blob image = res.getBodyAsBlob();
    base64Data =  EncodingUtil.base64Encode(image);
    System.debug('image= ' + image);

    Document docatt = new Document();
    docatt.Name = 'Chart 1.jpg';
    docatt.Body = EncodingUtil.base64Decode(base64Data);
    docatt.FOLDERID = '00l6F231005tqGi';
    docatt.IsPublic = true;

    insert docatt;

}

Image file that was saved:

Saved Image File

Adrian Larson
  • 149,971
  • 38
  • 239
  • 420
Luke Au
  • 179
  • 2
  • 15
  • 1
    Assuming the image1 URL you have works fine from a browser session then the problem will be a missing cookie with a Salesforce Session ID to authenticate the request. You will need to set the sid cookie to a valid Session ID. – Daniel Ballinger Apr 20 '17 at 02:34

1 Answers1

3

You will need to set a valid sid cookie on the request to authenticate it.

HttpRequest req = new HttpRequest();
//...
req.setHeader('Cookie', 'sid=' + UserInfo.getSessionId()+ ';');
//...

Also consider the HttpResponse to see what went wrong. E.g.

HttpResponse res = http.send(req);
System.debug('Status Code: ' + res.getStatusCode());
Daniel Ballinger
  • 102,288
  • 39
  • 270
  • 594