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
raz rraz r 

Attachments uploaded through Rest Api ,getting 500 Internal server error

Hi ,

We are trying to upload the attachmnets through REST api from Salesforce to appliction. We have recieved the below error.
System.HttpResponse[Status=Internal Server Error, StatusCode=500]
Please fidn the below code for your reference. please provide teh solution asap.

public class FiniWiseAttachmentClass {
     public static HTTPResponse uploadFile()
       list<Attachment> attch=[SELECT ContentType, Body, Name, ParentId, Id, OwnerId,Description,BodyLength FROM Attachment where ParentId in (select id from Analysis__c where Opportunity__c='0065C000002Q7fz')];
    system.debug('Attachment list'+attch);
    String boundary ='__boundary__rrr';
    String header ='--'+boundary+'n';
    String body='';    
   body +='Content-Disposition: form-data; name="data"; filename="'+attch[0].name+'"nContent-Type: application/octet-stream';
    String footer ='n--'+boundary+'--';
    // no trailing padding on header by adding ' ' before the last "nn" characters
    String headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+'nn'));
    //this ensures no trailing "=" padding
    header+=' ';
    headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+'nn'));
  //base64 encoded body
    String bodyEncoded = EncodingUtil.base64Encode(attch[0].body);
    //base64 encoded footer
    String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
    Blob bodyBlob =null;
    //last encoded body bytes
    String last4Bytes = bodyEncoded.substring(bodyEncoded.length()-4,bodyEncoded.length());
    //if the last 4 bytes encoded base64 ends with the padding character (= or ==) then re-encode those bytes with the footer
    //to ensure the padding is added only at the end of the body
    Blob decoded4Bytes = EncodingUtil.base64Decode(last4Bytes);
    HttpRequest tmp =new HttpRequest();
    String last4BytesFooter = tmp.getBody()+footer;
    bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded.substring(0,bodyEncoded.length()-4)+EncodingUtil.base64Encode(Blob.valueOf(last4BytesFooter)));
     system.debug('Body request'+bodyBlob);   
    bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);
        System.debug('Body request'+bodyBlob);
    //this a "public class CustomException extends Exception{}"
    throw newCustomException('File size limit is 3 MBytes');
    String Endpointurl= 'testurl';  

    HttpRequest req =new HttpRequest();
    req.setHeader('Content-Type','multipart/form-data; boundary='+boundary);
    Http http =new Http();
    HTTPResponse res = http.send(req);
    return res;


It's very urgent. Please suggest us. 
raz rraz r
Hi All,

Please provide the solution asap.