cowboy erlang  上传文件

-module(upload_handler).
-export([init/2]).

init(Req, Opts) ->
    %{ok, Headers, Req2} = cowboy_req:part(Req),
    %{ok, Data, Req3} = cowboy_req:part_body(Req2),
    %{file, <<"inputfile">>, Filename, ContentType, _TE}
    %    = cow_multipart:form_data(Headers),
    %io:format("Received file ~p of content-type ~p as follow:~n~p~n~n",
    %    [Filename, ContentType, Data]),
    
    Req3 = multipart(Req),
    io:format("rev...~n"),
    {ok, Req3, Opts}.


file_r(_Filename) ->
   case  file:open( _Filename, [raw, write, binary]) of
           {ok,IFile} ->
              io:format("open.ok~n"),
           IFile;
        _Error ->
            io:format("file ff~n"),
            error
   end.

multipart(Req) ->
    case cowboy_req:part(Req) of
        {ok, Headers, Req2} ->
            Req4 = case cow_multipart:form_data(Headers) of
                {data, _FieldName} ->
                    {ok, _Body, Req3} = cowboy_req:part_body(Req2),
                      Req3;
                {file, _FieldName, _Filename, _CType, _CTransferEncoding} ->
                    io:format("filename:~p~n",[_Filename]),
                    
                    Iff = file_r( _Filename ),
                    io:format("fdsfs:~p~n",[Iff]),
                    stream_file(Req2,Iff),
                    file:close(Iff)
            end,
            multipart(Req4);
        {done, Req2} ->
            Req2
    end.

stream_file(Req,Iff) ->
    case cowboy_req:part_body(Req) of
        {ok, _Body, Req2} ->
            file:write(Iff, _Body),
            Req2;
        {more, _Body, Req2} ->
            file:write(Iff, _Body),
            stream_file(Req2,Iff)
    end.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值