如何通过erlang cowboy下载文件?

时间:2014-08-24 13:09:44

标签: erlang cowboy

我想从浏览器下载文件,我尝试通过牛仔实现,但是我失败了,浏览器显示“重复从服务器收到的标题。”。我不知道,大家请帮助我。这是我的处理程序代码: `

%% @doc GET echo handler.
-module(toppage_handler2).

-export([init/3]).
-export([handle/2]).
-export([terminate/3]).

init(_Transport, Req, []) ->
    {ok, Req, undefined}.

handle(Req, State) ->
    {Method, Req2} = cowboy_req:method(Req),
    {Echo, Req3} = cowboy_req:qs_val(<<"echo">>, Req2),
    {ok, Req4} = echo(Method, <<Echo/binary, " I am there ">>, Req3),
    {ok, Req4, State}.

echo(<<"GET">>, undefined, Req) ->
    cowboy_req:reply(400, [], <<"Missing echo parameter.">>, Req);

%% the main part of download the file is here
%% I just want to download the file README.md
echo(<<"GET">>, Echo, Req) ->
    F = fun (Socket, Transport) ->
    Transport:sendfile(Socket, "priv/README.md")
    end,
    Req2 = cowboy_req:set_resp_body_fun(1024, F, Req),
     Req3 = cowboy_req:set_resp_header(<<"Content-Disposition">>, "GET", Req2),
    Req4 = cowboy_req:set_resp_header(<<"attachment;filename=\"README.md\"">>, "GET", Req3),
     Req5 = cowboy_req:set_resp_header(<<"Content-Length">>, "GET",  Req4),
     Req6 = cowboy_req:set_resp_header(<<"1024">>, "GET",  Req5),
    cowboy_req:reply(200, [
        {<<"content-type">>, <<"application/octet-stream">>}
    ], "", Req6);

echo(_, _, Req) ->
    %% Method not allowed.
    cowboy_req:reply(405, Req).

terminate(_Reason, _Req, _State) ->
    ok.`

2 个答案:

答案 0 :(得分:2)

Cowboy有一个用于提供静态文件的内置处理程序。 这里记录在案:

http://ninenines.eu/docs/en/cowboy/HEAD/guide/static_handlers/

并且在github上有例子:

https://github.com/ninenines/cowboy/tree/master/examples/static_world/src

这样,您不必手动设置标头,这样可以防止出错。

答案 1 :(得分:1)

这显然对OP来说太晚了,但也许它会帮助有人从谷歌那里找到这个。

您的问题是,您使用set_resp_body_fun功能覆盖了使用cowboy_req:reply/4设置的响应正文功能。您需要做的就是使用cowboy_req:reply/3调用替换该行,该调用未明确设置正文

cowboy_req:reply(200, [
    {<<"content-type">>, <<"application/octet-stream">>}
], Req6);

你会发现它有效。