[SalesForce] pre-populating apex:inputFile tag with attachment file

I'm using an apex:inputFile tag on a VF page to import files that are added as attachments to records. If the user returns to this VF page is it possible to show the apex:inputFile prepopulated with the current attachment for that record? That way the user can see the name of the file that is already uploaded and choose to replace it.

Right now when I put these raw merge fields on the VF page they display the correct info:

{!attachments[0].name}
{!attachments[0].body}

However, when I add them to the apex:inputFile it still says 'No file chosen'

<apex:inputFile fileName="{!attachments[0].name}" value="{!attachments[0].body}" />

Any suggestions? Is this even possible?

Thanks!

Best Answer

The apex:inputFile component gets generated as a html input type of file. You cannot set the value of that any way other than through the file chooser due to security reasons. This is enforced in the browser and is independent of Salesforce.

One other point: You generally do not want the body of the attachment in your view state ever, because it can easily lead to a situation where the view state limit is violated. You need to look at setting the attachment property to be transient and/or setting the body to null (before the page is rendered, after you submit it, validation failures, or any time the page is rendered and the value is set).

I suggest something like creating a link to the document next to the input, so that the user can click it to see the current value of it. Something along the lines of the following (note I didn't test this code out):

<apex:inputFile fileName="{!attachments[0].name}" value="{!attachments[0].body}" />
<apex:outputLink 
    value="{!URLFOR($Action.Attachment.Download, attachments[0].Id)}" target="_blank">
    {!attachments[0].name}
</apex:outputLink>