I need to get the URL to view an attachment in Apex. In Visualforce, I can use URLFOR($Action.Attachment.Download, a.id). In this case, I want to return a PageReference from an Apex method that sends the user over to the view attachment page.

I can manually build the link as '/servlet/servlet.FileDownload?file=' + a.Id , but I'd rather not hardcode that.

I tried using URL.getFileFieldURL(a.Id, 'Body') but I'm getting an error: Invalid parameter value "Body" for parameter "fieldName". The example looks like it is used on an Idea record (prefix 087). Maybe it doesn't work on Attachment records.

  • As I see from g00gle there is no other way rather than hardcode this url. Feb 20, 2014 at 20:44
  • In our recent experience we have also eventually "hardcoded" it. Perhaps consider a Custom Setting field instead to make it softer and more manageable? Feb 21, 2014 at 9:47

1 Answer 1


I haven't tested it, but how about URL.getFileFieldURL(string, string).

Returns the download URL for a file attachment.

You might need to work back to the entity that has a reference to the attachment in a field.

UPDATE This doesn't appear to work in practice. From the Summer 13 release notes:

We’ve also created a new Apex method, URL.getFileFieldURL that lets you retrieve the download URL for file attachments in custom implementations of Ideas.

So it might be that this method is only applicable to ideas.

Otherwise Dynamic apex/visualforce might help, but you would probably need to change from returning a PageRefernce. See Dynamic References to Action Methods Using $Action

  • a nice underutilized gem there! Feb 20, 2014 at 21:03
  • Hmm, looks promising, but I tried URL.getFileFieldURL(attc.Id, 'Body'); but I'm getting an error: Invalid parameter value "Body" for parameter "fieldName". Also fails with AttachmentBody Feb 20, 2014 at 21:06
  • Yes, it doesn't work :-( Feb 20, 2014 at 21:16
  • Damn, It looked so promising. Back to the drawing board. Feb 20, 2014 at 21:20

You must log in to answer this question.

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