I need to send 2 files to an external system in multipart/form-data using REST API. I'm able to do it using postman. enter image description here

I have 2 attachments stored in Attachments object. I need to send both files (as shown in attached screenshot) in single request. Can you please help me to compose the same request using APEX?

I took reference from this post: How can I compose a multipart/form-data request?

My Code:

//  Compose the form
string form64 = '';

form64 += vNHttpFormBuilder.WriteBoundary();

//file 1
vNHttpFormBuilder.WriteFileResult result1 = vNHttpFormBuilder.WriteFile('file', fileName, fileMimeType, fileBlob);
form64 += result1.Content;
form64 += vNHttpFormBuilder.WriteBoundary(result1.EndingType);

//file 2
vNHttpFormBuilder.WriteFileResult result2 = vNHttpFormBuilder.WriteFile('file', fileName, fileMimeType, fileBlob);
form64 += result2.Content;
form64 += vNHttpFormBuilder.WriteBoundary(result2.EndingType);

blob formBlob = EncodingUtil.base64Decode(form64);
string contentLength = string.valueOf(formBlob.size());

//  Compose the http request
HttpRequest httpRequest = new HttpRequest();

httpRequest.setHeader('Connection', 'keep-alive');
httpRequest.setHeader('Content-Length', contentLength);
httpRequest.setHeader('Content-Type', contentType);
  • @sfdcfox Thanks for your response. I have seen the question. In my case, I need to attach 2 files.
    – Manoj
    Commented Oct 17, 2020 at 20:23
  • It's no different than one file--you just repeat the boundary and add more headers.
    – sfdcfox
    Commented Oct 17, 2020 at 20:24
  • Usually it is better not to send it using Salesforce. You would want another automation to do that (retrieve the file from Salesforce and upload it elsewhere) for you. Mostly because of transaction memory limitations. Commented Oct 17, 2020 at 20:30
  • @sfdcfox I have attached the code to question which I tried.
    – Manoj
    Commented Oct 17, 2020 at 20:39


Browse other questions tagged .