Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Go:
- func randomHex(length int) string {
- buffer := make([]byte, length)
- _, err := rand.Read(buffer)
- if err != nil {
- panic(err)
- }
- return hex.EncodeToString(buffer)
- }
- func saveToDb(filename string) {
- file, err := os.Open(filename)
- if err != nil {
- panic(err)
- }
- defer file.Close()
- var buffer = make([]byte, 128*1024)
- for {
- _, err := file.Read(buffer)
- if err == io.EOF {
- break
- }
- if err != nil {
- panic(err)
- }
- digest := sha256.Sum256(buffer)
- id := hex.EncodeToString(digest[:])
- rows, err := db.Query("INSERT INTO chunks(id, data) VALUES (?, ?)", id, buffer)
- if err != nil {
- panic(err)
- }
- defer rows.Close()
- }
- }
- func fileUpload(w http.ResponseWriter, r *http.Request) {
- filename := randomHex(32)
- file, err := os.Create(filename)
- if err != nil {
- panic(err)
- }
- io.Copy(file, r.Body)
- file.Close()
- saveToDb(filename)
- w.WriteHeader(http.StatusNoContent)
- }
- Erlang:
- -module(files_post_handler).
- -export([init/3, terminate/3, handle/2]).
- init(_, Req, _) ->
- {ok, Req, []}.
- write_body(File, Req0) ->
- case cowboy_req:body(Req0) of
- {ok, Data, Req} ->
- ok = file:write(File, Data),
- Req;
- {more, Data, Req} ->
- ok = file:write(File, Data),
- write_body(File, Req)
- end.
- save_body(Req0) ->
- Filename = utils:rand_hex(32),
- {ok, File0} = file:open(Filename, [write, raw, binary, exclusive]),
- Req = write_body(File0, Req0),
- file:close(File0),
- {Req, Filename}.
- chunk_to_db(Data) ->
- Id = utils:bin_to_hex(crypto:hash(sha256, Data)),
- {ok, 1} = sql:q("INSERT INTO chunks(id, data) VALUES ($1, $2)", [Id, Data]),
- {ok, Id}.
- chunks_to_db(File0, Chunks) ->
- case file:read(File0, 128 * 1204) of
- {ok, Data} ->
- {ok, Id} = chunk_to_db(Data),
- chunks_to_db(File0, [Id | Chunks]);
- eof ->
- {ok, lists:reverse(Chunks)}
- end.
- save_to_db(Filename) ->
- {ok, File0} = file:open(Filename, [read, raw, binary, exclusive]),
- chunks_to_db(File0, []).
- handle(Req0, State) ->
- sql:q("INSERT INTO test(test) VALUES(?)", [<<"TEST">>]),
- {Req1, Filename} = save_body(Req0),
- {ok, Chunks} = save_to_db(Filename),
- io:format("~p~n", [Chunks]),
- {ok, Req} = cowboy_req:reply(
- 204,
- [
- %% {<<"connection">>, <<"close">>}
- ],
- Req1),
- {ok, Req, State}.
- terminate(_, _, _) ->
- ok.
Advertisement
Add Comment
Please, Sign In to add comment