https://kotlinlang.org logo
#http4k
Title
# http4k
a

andyg

11/14/2020, 1:38 AM
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

dave

11/14/2020, 1:16 PM
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

andyg

11/15/2020, 6:32 AM
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
2 Views