0

I have one lightning component which is used to show all notes and attachments In case of Attachments it needs to download it. Its working fine for CSV format but in case of JPEG format it is not downloading, instead it is opening in same window

<aura:iteration var="n" items="{!v.Attachments}" >
<ui:outputURL value="{!'/servlet/servlet.FileDownload?file='+n.attachmentId}" label="View File"/>
</aura:iteration>
2

The reason why your images are view-able rather than downloadable is due to the "Content-Disposition" attribute that is set on the images when the file is being served.

There a couple of ways to enforce the download ,

The most easiest way is to get rid of the <ui:outputURL> tag and use a traditional anchor tag. Like follows

<aura:iteration var="n" items="{!v.Attachments}" >
    <a href="{!'/servlet/servlet.FileDownload?file='+n.attachmentId}" download="myimage.jpg">
        View File
    </a>
</aura:iteration>

The "download" attribute in the anchor tag will enforce the download. This should ideally work for all the file types.

I really do not see the need for ui:outputURL in this scenario. But just in case you need it, then you can do a conditional rendering with aura:if based on the "ContentType" and show ui:outputURl and anchor tag based on file ypes. Something like follows

<aura:if isTrue="{!n.ContentType == 'image/jpeg' ? true : false}">
    <!-- The Anchor Tag Logic -->
    <aura:set attribute="else">
        <!-- Your ui:outputURL logic -->
    </aura:set>
</aura:if>

Do consider the performance trade-off while using aura:if and else when you have a large volume of attachments to iterate.

Another approach would be to use javascript, capture the click event on ui:outputURL, get the URL for the attachment, validate the attachment file type (.jpg or .pdf etc ), then create a dynamic anchor tag element in the controller as shown in first method and simulate a click event on the same. This would also trigger a download. Like i mentioned earlier - this would be a bit cumbersome, you should approach with the first method, it would be easier to maintain and implement.

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.