When using the Soap API to work with an Attachment how can I determine the correct file extension when saving the Body contents locally?


I created a test attachment on an Account from a PDF. The default name field includes the file extension as it was uploaded. However, the user is free to edit this field and remove the ".pdf" suffix.

Attachment.Name includes the file extension by default

The ContentType field contains what I'd think of as the MIME type. I could maintain a mapping from the ContentType to the file extension, but the relationship isn't 1:1.

The following MIME types map to multiple possible file extensions:

  • application/vnd.ms-excel - xls, xla, xlc, xlm, xlt, xlw
  • application/postscript - ai, eps, ps
  • application/vnd.ms-powerpoint - ppt, pot, pps

If I want to save the bytes pulled out of the Body field somewhere locally I can't determine the correct file extension to use if the user has edited the attachment name. I can make a reasonable guess, but it might not be correct. In some cases it may not be an issue, as the target application will still correctly interpret the file.

  • I'm curious about this as well and suspect there's nothing you can do other than a mapping. I change file extensions on my windows machine and it warns me that the file may become unusable and prompts me for confirmation. Perhaps you can do that as well. Commented Oct 9, 2012 at 1:22
  • @PeterKnolle Did you ever found a solution for this one ? Commented Jan 12, 2018 at 7:39

1 Answer 1


I am fairly certain you're out of luck here, and your best bet is to make a best guess when the MIME type does not match the extension. I would generally use the user's uploaded filename first, since (unless you're dealing with nefarious users) should have something that worked for the user. I would only rely on MIME type when there is no extension - but I also suspect in that case that Salesforce may not correctly store MIME type?

Short of writing code that parses the Blob and attempts to match it against known headers for file types (nightmare unless you're dealing with a few very common disambiguation cases), I think you are out of luck.

I'm curious to know how poor the data you have in the Name field is -- in most orgs I have dealt with it would be "good enough" for saving down to a filesystem for general consumption.

  • Yes, in the vast majority of cases the original file extension is still in the name, and failing that the ContentType gives a reasonable default to fall back to. I just tried uploading the same PDF with the extension removed. The ContentType came back blank. Commented Oct 9, 2012 at 19:21
  • I'm guessing the SFDC developer who made the upload feature faced the same sort of conundrum you do now :)
    – jkraybill
    Commented Oct 10, 2012 at 1:36

You must log in to answer this question.

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