Hey Niko,
The nice thing about most (all?) browsers is that if you do a redirect
to a static file, the browser will just download the file but keep you
on the site.
So that means that you could make the body of the "download page" be
whatever you want, and somewhere in there, do a
wf:redirect("
http://url/to/your/file").
That should ensure that the page gets rendered as you want and the
download happens.
That said, if you really want to have Nitrogen stream the file rather
than either letting the webserver handle it or having a reverse proxy
like nginx deal with your static files, you can make a separate module
(called something like downloads) and have the main() function do all
the things you previously had your download() function do.
You can do some URL trickery with wf:path_info() to determine which
file you're retrieving if you have a database or something mapping
some kind of file ID to an actual file on the filesystem.
Say you wanted to do some kind of download like
http://whatever/download/34543756743/my-file.bin
For example, you could do something like this for your download module.
-module(download).
-include_lib("nitrogen_core/include/wf.hrl").
main() ->
Path = wf:path_info(),
case re:match("^(\\d+)/.*",Path,[{capture,all_but_first,binary}]) of
{match, [ID]} -> serve_file(ID);
nomatch -> "Not Found"
end.
serve_file(ID) ->
File = my_file_mapper:get_file_from_id(ID);
download(File).
%% Using most of your download() function
download(FileName) ->
wf:content_type("application/octet-stream"),
wf:header("Content-Disposition"," attachment; filename=\"myfile.pdf\""),
wf:header("Content-Transfer-Encoding", "binary"),
wf:header("Accept-Ranges", "bytes"),
{ok,Data} = file:read_file(FileName),
Data.
That's typically how I deal with a download module that must be served
from Nitrogen, though it's more common for me to redirect to something
like Amazon S3 storage.
It should go without saying that you want to be careful with this
since you're reading the entire file into memory this way with
file:read_file/1, while the webservers like cowboy and yaws will
actually stream the file from disk if it's being served from one of
the config-defined static directories.
-Jesse
--
Jesse Gumm
Owner, Sigma Star Systems
414.940.4866 ||
sigma-star.com || @jessegumm