Search code examples
csvdownloadcoldfusioncffile

ColdFusion allow user to download CSV file


I am trying to allow the user to download a CSV file from the app. I have googled this a lot and as with almost any coldfusion issue I can't find much. Here is what I am trying:

<cfset yourFileName="\\10.21.2.187\devintranet\WebSite\Audit_Web\AuditWeb\temp\file.csv">
<cffile action="read" file="#yourFileName#" variable="myFile">

<cfheader name="content-disposition" value="attachment; filename=#listLast(myFile, "\")# />
<cfcontent type="application/msexcel" variable="#myFile#" reset="true" />

This is the correct filepath:

temp/file.csv

and this is the file name:

Right now I am getting the error: 403 forbidden. I have no idea what is wrong and what is right about this. I'm just using code I found online. Any advice at all would be greatly appreciated.


Solution

  • Determine which file you want to download:

    <cfset yourFileName="\\10.21.2.187\devintranet\WebSite\Audit_Web\AuditWeb\temp\file.csv">
    

    Read the file into a CF variable:

    <cffile action="read" file="#yourFileName#" variable="myFile">
    

    Send the file to the browser using the correct mime-type and file name:

    <cfheader name="content-disposition" value="attachment; filename=#listLast(myFile, '\')#" />
    <cfcontent type="application/msexcel" variable="#myFile#" reset="true" />
    

    Then there's no need for <cflocation>, the request will end once the file has been pushed to the browser.

    Update: According to CFDocs, text/csv isn't an allowed type. It should allow any proper mime-type, apparently it doesn't. Check that link for allowed values for type.

    Update 2: text/csv was just fine. The value attribute of cfheader wasn't closed correctly. Had to change the listLast() to use single quotes and add a closing double quote.