Best way to serve a file download? Not using `stat...
# http4k
a
Best way to serve a file download? Not using
static
because there's some validation involved (or maybe file created dynamically). Based on an earlier Slack thread, I came up with this:
Copy code
return if (<some validation code here>)
  Response(Status.OK)
    .header("Content-Type", "application/zip") // "application/octet-stream")
    .header("Content-Disposition", "attachment; filename=${myFileToServe.file.substringAfterLast("/")}")
    .header("Content-Length", myFileToServe.openConnection().contentLength.toString())
    .body(myFileToServe.openStream())
else Response(Status.UNAUTHORIZED)
d
As long as that's serving all of the headers you need then looks ok. You can extract the validation to a Filter if you wanted to separate it out
also - do you need to set the content length? might be worth checking - can possibly emit
a
thanks. when I need to download files, sometimes the browser reports something like
15mb of 60mb (25%)
, other times it doesn't report the full size. I assumed knowing the full size and percentage was only possible when content-length is specified. don't know for sure but doesn't seem to hurt adding it in