Skip to content

Commit

Permalink
Added upload example
Browse files Browse the repository at this point in the history
  • Loading branch information
yhirose committed Nov 28, 2019
1 parent 6f58dc7 commit 448de6a
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 2 deletions.
7 changes: 5 additions & 2 deletions example/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ OPENSSL_DIR = /usr/local/opt/openssl
OPENSSL_SUPPORT = -DCPPHTTPLIB_OPENSSL_SUPPORT -I$(OPENSSL_DIR)/include -L$(OPENSSL_DIR)/lib -lssl -lcrypto
ZLIB_SUPPORT = -DCPPHTTPLIB_ZLIB_SUPPORT -lz

all: server client hello simplesvr redirect benchmark
all: server client hello simplesvr upload redirect benchmark

server : server.cc ../httplib.h Makefile
$(CXX) -o server $(CXXFLAGS) server.cc $(OPENSSL_SUPPORT) $(ZLIB_SUPPORT)
Expand All @@ -19,6 +19,9 @@ hello : hello.cc ../httplib.h Makefile
simplesvr : simplesvr.cc ../httplib.h Makefile
$(CXX) -o simplesvr $(CXXFLAGS) simplesvr.cc $(OPENSSL_SUPPORT) $(ZLIB_SUPPORT)

upload : upload.cc ../httplib.h Makefile
$(CXX) -o upload $(CXXFLAGS) upload.cc $(OPENSSL_SUPPORT) $(ZLIB_SUPPORT)

redirect : redirect.cc ../httplib.h Makefile
$(CXX) -o redirect $(CXXFLAGS) redirect.cc $(OPENSSL_SUPPORT) $(ZLIB_SUPPORT)

Expand All @@ -30,4 +33,4 @@ pem:
openssl req -new -key key.pem | openssl x509 -days 3650 -req -signkey key.pem > cert.pem

clean:
rm server client hello simplesvr redirect *.pem
rm server client hello simplesvr upload redirect *.pem
49 changes: 49 additions & 0 deletions example/upload.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
//
// upload.cc
//
// Copyright (c) 2019 Yuji Hirose. All rights reserved.
// MIT License
//

#include <httplib.h>
#include <iostream>
#include <fstream>
using namespace httplib;
using namespace std;

const char* html = R"(
<form id="formElem">
<input type="file" name="file" accept="image/*">
<input type="submit">
</form>
<script>
formElem.onsubmit = async (e) => {
e.preventDefault();
let res = await fetch('/post', {
method: 'POST',
body: new FormData(formElem)
});
console.log(await res.text());
};
</script>
)";

int main(void) {
Server svr;

svr.Get("/", [](const Request & /*req*/, Response &res) {
res.set_content(html, "text/html");
});

svr.Post("/post", [](const Request & req, Response &res) {
auto file = req.get_file_value("file");
cout << "file: " << file.offset << ":" << file.length << ":" << file.filename << endl;

ofstream ofs(file.filename, ios::binary);
ofs << req.body.substr(file.offset, file.length);

res.set_content("done", "text/plain");
});

svr.listen("localhost", 1234);
}

0 comments on commit 448de6a

Please sign in to comment.