[SalesForce] Changing Attachments “content-disposition” from inline to attachment

Well this is a concept and was trying to implement the same in VF. In salesforce Attachments are served with content-disposition = inline, this makes the attachment to display in the browser.

Now plan was to change the content-disposition to attachment by a "Proxy VF Page". The code looks something like this

public Pagereference downloadit() {
    Pagereference pageRef = new Pagereference('https://c.ap1.content.force.com/servlet/servlet.FileDownload?file=00P90000006T0ZH');
    pageref.getHeaders().put('content-disposition', 'attachment; filename=' + 'myfile.png');
    pageref.setRedirect(false);
    return pageref;
}

<apex:page controller="AttachmentDownloadProxy_Con" action="{!downloadIt}">

</apex:page>

But it doesn't seem to work. The file gets downloaded but seems to be corrupted. Any Idea ?

On checking the file source, this is what I got

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>
    <meta HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">





    <script>
        if (this.SfdcApp && this.SfdcApp.projectOneNavigator) {
            SfdcApp.projectOneNavigator.handleRedirect('https://c.ap1.content.force.com/servlet/servlet.FileDownload?file=00P90000006T0ZH');
        } else
         if (window.parent.location.replace) {
            window.parent.location.replace('https://c.ap1.content.force.com/servlet/servlet.FileDownload?file=00P90000006T0ZH');
        } else {;
            window.parent.location.href = 'https://c.ap1.content.force.com/servlet/servlet.FileDownload?file=00P90000006T0ZH';
        }
    </script>

</head>


</html>

Best Answer

I think you'll find the contents of your file is actually HTML for a client-side redirect!

Might be tricky to "proxy" the file in this way, but you can change the Content-Type of your attachment to application/octet-stream to force download instead of display:

Try this:

Attachment attachment = new Attachment(
    Id = '00P90000006T0ZH',
    ContentType = 'application/octet-stream'
);

update attachment;

then link to it as normal and you'll get it as a downloaded file.

Related Topic