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

1
  • 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. Apr 20 '17 at 2:34
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());
4
  • just wondering if there way? It's because I want to put his into a scheduler to insert the image into the Document Folder and I might not be online at that point of time that it upload the image file
    – Luke Au
    Apr 20 '17 at 3:03
  • Establishing a session from a scheduled job is a whole other problem. Have a search, as there are other questions that have addressed that issue. Apr 20 '17 at 3:27
  • The last time I tried putting 2 HTTP method in the same class I had an error. The other method that was given I don't understand the codes to implement it into the scheduler.
    – Luke Au
    Apr 20 '17 at 4:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.