Search code examples
httphaskellihp

Is there an alternative to createTemporaryDownloadUrl that doesn't require file storage on the server?


I am trying to export a particular string as a csv file and I want the user to be able to download this file. IHP has the createTemporaryDownloadUrl function that takes in a StoredFile and then creates a temporary download link. The problem is, I don't want to store this CSV file on the server since it requires additional overhead, such as deleting the file after the temporary download link has expired.

I am able to render the text variable using renderPlain, but I'm not entirely sure how to automate the downloading process (since the user would have to right click, download as, and then rename the file themselves)

I first tried using the regular createTemporaryDownloadUrl method by storing the file, but there is no easy way of deleting the file after the temporary download url expires. I'm able to display the CSV contents as a plain text file, but there is no obvious way of having the user download it.


Solution

  • In your action, you can set the Content-Disposition header in order to trigger the download of a variable of type Text. In this example, I'll use fileName and fileContent to be the file's name and content, respectively:

    ...
        action DownloadCSV = do
          ...
          -- These could be from the database, etc
          let fileName = "MyFile.csv"
              fileContent = "Name, Age\nBob, 30"
          setHeader ("Content-Disposition", "attachment; filename = " ++ cs fileName)
          renderPlain $ cs fileContent
    ...
    

    setHeader is used to tell the browser to download a file with the given name, and then renderPlain sends the browser the file's content.

    Of course, this can be used for any type of text file by changing the filename to a different file extension.

    Hope this helps!