Skip to content

Commit 448de6a

Browse files
committed
Added upload example
1 parent 6f58dc7 commit 448de6a

File tree

2 files changed

+54
-2
lines changed

2 files changed

+54
-2
lines changed

example/Makefile

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ OPENSSL_DIR = /usr/local/opt/openssl
55
OPENSSL_SUPPORT = -DCPPHTTPLIB_OPENSSL_SUPPORT -I$(OPENSSL_DIR)/include -L$(OPENSSL_DIR)/lib -lssl -lcrypto
66
ZLIB_SUPPORT = -DCPPHTTPLIB_ZLIB_SUPPORT -lz
77

8-
all: server client hello simplesvr redirect benchmark
8+
all: server client hello simplesvr upload redirect benchmark
99

1010
server : server.cc ../httplib.h Makefile
1111
$(CXX) -o server $(CXXFLAGS) server.cc $(OPENSSL_SUPPORT) $(ZLIB_SUPPORT)
@@ -19,6 +19,9 @@ hello : hello.cc ../httplib.h Makefile
1919
simplesvr : simplesvr.cc ../httplib.h Makefile
2020
$(CXX) -o simplesvr $(CXXFLAGS) simplesvr.cc $(OPENSSL_SUPPORT) $(ZLIB_SUPPORT)
2121

22+
upload : upload.cc ../httplib.h Makefile
23+
$(CXX) -o upload $(CXXFLAGS) upload.cc $(OPENSSL_SUPPORT) $(ZLIB_SUPPORT)
24+
2225
redirect : redirect.cc ../httplib.h Makefile
2326
$(CXX) -o redirect $(CXXFLAGS) redirect.cc $(OPENSSL_SUPPORT) $(ZLIB_SUPPORT)
2427

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

3235
clean:
33-
rm server client hello simplesvr redirect *.pem
36+
rm server client hello simplesvr upload redirect *.pem

example/upload.cc

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
//
2+
// upload.cc
3+
//
4+
// Copyright (c) 2019 Yuji Hirose. All rights reserved.
5+
// MIT License
6+
//
7+
8+
#include <httplib.h>
9+
#include <iostream>
10+
#include <fstream>
11+
using namespace httplib;
12+
using namespace std;
13+
14+
const char* html = R"(
15+
<form id="formElem">
16+
<input type="file" name="file" accept="image/*">
17+
<input type="submit">
18+
</form>
19+
<script>
20+
formElem.onsubmit = async (e) => {
21+
e.preventDefault();
22+
let res = await fetch('/post', {
23+
method: 'POST',
24+
body: new FormData(formElem)
25+
});
26+
console.log(await res.text());
27+
};
28+
</script>
29+
)";
30+
31+
int main(void) {
32+
Server svr;
33+
34+
svr.Get("/", [](const Request & /*req*/, Response &res) {
35+
res.set_content(html, "text/html");
36+
});
37+
38+
svr.Post("/post", [](const Request & req, Response &res) {
39+
auto file = req.get_file_value("file");
40+
cout << "file: " << file.offset << ":" << file.length << ":" << file.filename << endl;
41+
42+
ofstream ofs(file.filename, ios::binary);
43+
ofs << req.body.substr(file.offset, file.length);
44+
45+
res.set_content("done", "text/plain");
46+
});
47+
48+
svr.listen("localhost", 1234);
49+
}

0 commit comments

Comments
 (0)