mirror of
https://github.com/yhirose/cpp-httplib.git
synced 2025-05-15 01:08:27 +00:00
Added upload example
This commit is contained in:
parent
6f58dc728f
commit
448de6a9c6
2 changed files with 54 additions and 2 deletions
49
example/upload.cc
Normal file
49
example/upload.cc
Normal file
|
@ -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);
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue