Find your content:

Search form

You are here

Determine the correct file type extension for an Attachment


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/ - xls, xla, xlc, xlm, xlt, xlw
  • application/postscript - ai, eps, ps
  • application/ - 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.

Attribution to: Daniel Ballinger

Possible Suggestion/Solution #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.

Attribution to: jkraybill
This content is remixed from stackoverflow or stackexchange. Please visit

My Block Status

My Block Content