I was having trouble adding Files to a formdata and my question (How to add a file to a formdata for an api in apex) was closed because there were other solutions that should work. I've tried Compose a multipart/form-data request from apex without base64 encode and How can I compose a multipart/form-data request? (though I had to edit the class a bit) I still get the 422 error.

//I used
.writeFile( 'Files', 'Lease.pdf', EncodingUtil.base64Encode(file)) //From the pdf.getContentAsPdf() 

req.setHeader( 'Connection', 'keep-alive' );
req.setHeader( 'Content-Length', String.valueOf(formData.size()) );
req.setHeader( 'Content-Type', HttpHexFormBuilder.GetContentType() );

//And even the manual way
body += 'name=\"Files\"; filename=\"Lease.pdf\"; Content-Type=\"application/pdf\"\r\n\r\n'+EncodingUtil.base64Encode(file)+'\r\n';


I even tried using the VersionData of a file that I already have

ContentVersion cv = [Select VersionData from ContentVersion where id = '068Do000002J0ArIAK'];

.writeFile( 'Files', 'lease2.pdf', EncodingUtil.base64Encode(cv.VersionData))

And still nothing. It looks like it should work but I keep getting the same 422 error.

  • I didn't believe using FormData was supported from apex. We uploaded files with multipart/form-data from our LWC javscript files using the fetch api. I have examples of that if you'd like.
    – JRiffe
    Mar 23 at 20:33
  • Yeah sorry I keep using formdata and multipart/form-data interchangeably. I'm doing this using the multipart/form-data with the boundaries and stuff. Mar 23 at 20:52
  • Yes, I use them interchangeably too. Is it something you can do from JavaScript or is your requirement specifically from apex?
    – JRiffe
    Mar 23 at 21:03
  • I get a cors error when I do it from javascript and I was advised to do it from apex. Mar 24 at 16:04
  • Ah, yes. I got many pre-flight CORS issues as well, but we control the server we are accessing so was able to get around that. You could also specify no-cors, but we didn't continue to go down that route since we did have access modify the service.
    – JRiffe
    Mar 24 at 20:46

1 Answer 1


You can't just drop base-64 into the content area without declaring it as such:

Content-Disposition: form-data; name="Files" filename="Lease.pdf"
Content-Type: application/pdf;base64

<<base64 encoded data here>>

Not all servers support this kind of content, however. You will likely need to encode the entire payload to hexadecimal, then convert it to a blob before sending it. You'll have a limit of approximately 3MB of file data if you use hexadecimal, which is easier to work with (no padding to figure out), but takes twice the extra space of the original file, instead of base64's 33% space increase.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .