Question

I need to download files stored on a database. I believe snap has file utils which help with file upload and download but it only deals with files resident on a filesystem.

I was given advice on the snap IRC to writeBS function to push the data to the browser. Also, I was told to modify HTTP header so that browser treats the data as a file and brings save/open dialog. I got to play with it today and have more questions.

I have this so far:

getFirst :: AppHandler ()
getFirst = do
  modifyResponse $ setContentType "application/octet-stream"  -- modify HTTP header
  result <- eitherWithDB $ fetch (select [] "files")  -- get the file from db
  let doc = either (const []) id result  -- get the result out of either
      fileName = at "name" doc  -- get the name of the file
      Binary fileData  = at "blob" doc  -- get the file data
  writeBS fileData

Can you please tell me if this is the correct way of doing it?

It works but few things are missing:

  • How do I pass the file name and file type to the browser?
  • How do I set the Content-Disposition?

So I need to be able to set something like this:

Content-Disposition: attachment; filename=document.pdf
Content-Type: application/pdf

How can I do this?

Was it helpful?

Solution

You can set an arbitrary header of the response using modifyResponse in combination with setHeader (both from Snap.Core). Like this:

modifyResponse $ setHeader "Content-disposition" "attachment; filename=document.pdf"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top