NAWA 0.9
Web Application Framework for C++
File.cpp
Go to the documentation of this file.
1/*
2 * Copyright (C) 2019-2022 Tobias Flaig.
3 *
4 * This file is part of nawa.
5 *
6 * nawa is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Lesser General Public License,
8 * version 3, as published by the Free Software Foundation.
9 *
10 * nawa is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public License
16 * along with nawa. If not, see <https://www.gnu.org/licenses/>.
17 */
18
24#include <cstring>
25#include <fstream>
26#include <nawa/Exception.h>
27#include <nawa/request/File.h>
28
29using namespace nawa;
30using namespace std;
31
32struct File::Data {
33 string filename;
34 string contentType;
35 shared_ptr<char[]> dataPtr;
36 size_t size = 0;
37
38 Data(shared_ptr<char[]> dataPtr, size_t size) : dataPtr(std::move(dataPtr)), size(size) {}
39};
40
42
44
46
48
50
52
53NAWA_COMPLEX_DATA_ACCESSORS_IMPL(File, contentType, string)
54
55File::File(std::shared_ptr<char[]> dataPtr, size_t size) {
56 data = make_unique<Data>(std::move(dataPtr), size);
57}
58
59File::File(std::string const& data) {
60 shared_ptr<char[]> dataPtr(new char[data.size()]);
61 memcpy(dataPtr.get(), data.c_str(), data.size());
62 this->data = make_unique<Data>(std::move(dataPtr), data.size());
63}
64
65size_t File::size() const noexcept {
66 return data->size;
67}
68
69std::string File::toString() const {
70 return {data->dataPtr.get(), data->size};
71}
72
73void File::writeToDisk(std::string const& path) const {
74 ofstream outfile;
75 ios_base::iostate exceptionMask = outfile.exceptions() | ios::failbit;
76 outfile.exceptions(exceptionMask);
77 try {
78 outfile.open(path, ofstream::out | ofstream::binary);
79 outfile.write(data->dataPtr.get(), data->size);
80 outfile.close();
81 } catch (ios_base::failure const& e) {
82 throw Exception(__PRETTY_FUNCTION__, 1, "Could not write file to disk.", e.what());
83 }
84}
Exception class that can be used by apps to catch errors resulting from nawa function calls.
Container for (especially POST-submitted) files.
size_t size() const noexcept
Definition: File.cpp:65
void writeToDisk(std::string const &path) const
Definition: File.cpp:73
std::string toString() const
Definition: File.cpp:69
#define NAWA_DEFAULT_DESTRUCTOR_IMPL(Class)
Definition: macros.h:36
#define NAWA_COPY_CONSTRUCTOR_IMPL(Class)
Definition: macros.h:46
#define NAWA_COMPLEX_DATA_ACCESSORS_IMPL(Class, Member, Type)
Definition: macros.h:144
#define NAWA_MOVE_ASSIGNMENT_OPERATOR_IMPL(Class)
Definition: macros.h:98
#define NAWA_COPY_ASSIGNMENT_OPERATOR_IMPL(Class)
Definition: macros.h:56
#define NAWA_MOVE_CONSTRUCTOR_IMPL(Class)
Definition: macros.h:88
Definition: AppInit.h:31