[SalesForce] Get Link to View Attachment in Apex

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.

Best Answer

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

Related Topic