2

I stumbled across an Apex method in the documentation recently that would generate a URL for the download link for a standard Attachment, with a name something like getDownloadLink(). I don't remember the System class or what parameters it took, but I'd prefer using that in the backend to hardcoding

'/servlet/servlet.FileDownload?file='+myAttachmentId

Does anyone know where I can find this method? I made a mental, but not physical, note of its location in the docs... :(

1 Answer 1

3

You're looking for getFileFieldUrl from the URL Class.

getFileFieldURL(entityId, fieldName)

Returns the download URL for a file attachment.

Signature

public static String getFileFieldURL(String entityId, String fieldName)

Parameters

entityId

Type: String

Specifies the ID of the entity that holds the file data.

fieldName

Type: String

Specifies the API name of a file field component, such as AttachmentBody.

Return Value

Type: String

Usage

Example:

Example

 String fileURL =
 URL.getFileFieldURL(
     '087000000000123' ,
     'AttachmentBody');
3
  • It only works with Ideas as mentioned by Daniel here?
    – Raul
    Oct 18, 2017 at 11:23
  • @RahulSharma it works on other types, too. It used to be limited, but had since had other types added. It's a pretty handy method.
    – sfdcfox
    Oct 18, 2017 at 14:00
  • This method doesn't work for Attachment. If we try to execute it System.debug( URL.getFileFieldURL( '00P1s000000diCg' , 'Body') ); it would fail with error System.HandledException: Invalid parameter value \"Body\" for parameter \"fieldName\" . Is there any other way rather than building URL explicitly with '/servlet/servlet.FileDownload?file=' + a.Id ? Which attachments does support this method if it doesn't support the standard Attachment object?
    – Patlatus
    Jul 24, 2020 at 8:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.