How do I upload an attachment to a document in Cou

2019-04-08 17:19发布

问题:

I have used curl to upload an image file Penguins.jpg. For example: C:\curl>curl -vX PUT -H "Content-Type: image/jpeg" http://localhost:5984/DBNAME/DOCID/Penguins?rev=LATEST_REVISION --data-binary @Penguins.jpg

and it worked...

So, how can I achieve the same using ibrowse? ===============================

回答1:

Naturally, a file upload is an HTTP POST . Now lets first write piece of Erlang code which does HTTP/1.1 POST with Ibrowse .

%% Assumes Ibrowse application is in Code path
ensure_ibrowse()->
    case whereis(ibrowse) of
        undefined -> ibrowse:start();
        _ -> ok
    end.
post(Link,Data,Headers)-> ensure_ibrowse(), try ibrowse:send_req(Link,Headers,post,Data) of { _, _, _,Result} -> io:format("\n\tFile Uploaded. Return: ~p~n",[Result]); EE -> {error,EE} catch XX:XX2 -> {error,XX,XX2} end.

From there, lets do our Couch DB thing.

-define(Link,"http://localhost:5984/DBNAME/DOCID/Penguins?rev=LATEST_REVISION").
%% File_path must be a valid file ! upload_file(Full_file_path)-> case file:read_file(Full_file_path) of {ok,Binary} -> post(?Link,Binary,[{"Content-Type","image/jpeg"}]); Error -> Error end.

There you go ! All you need to do is to customize your Macro Link to fit your couch DB settings and you're good to go !