|
14 | 14 |
|
15 | 15 | #include <exception> |
16 | 16 |
|
| 17 | +namespace { |
| 18 | + |
| 19 | +QByteArray resolveMimeType(const QString &fileName, const QMimeDatabase *mimeDb) |
| 20 | +{ |
| 21 | + const QMimeType mime = mimeDb->mimeTypeForFile(fileName); |
| 22 | + |
| 23 | + #if ((QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) && QT_VERSION < QT_VERSION_CHECK(5, 15, 11)) || \ |
| 24 | + (QT_VERSION >= QT_VERSION_CHECK(6, 2, 0) && QT_VERSION < QT_VERSION_CHECK(6, 5, 0))) |
| 25 | + // Workaround https://bugreports.qt.io/browse/QTBUG-97392 for affected Qt versions |
| 26 | + if (mime.name() == QStringLiteral("application/x-extension-html")) |
| 27 | + { |
| 28 | + return QByteArrayLiteral("text/html"); |
| 29 | + } |
| 30 | + #endif |
| 31 | + |
| 32 | + const QByteArray mimeName = mime.name().toLocal8Bit(); |
| 33 | + if (mime.isValid() && !mime.isDefault() && !mimeName.isEmpty()) |
| 34 | + { |
| 35 | + return mimeName; |
| 36 | + } |
| 37 | + |
| 38 | + const QString suffix = QFileInfo(fileName).suffix().toLower(); |
| 39 | + if (suffix == QStringLiteral("js") || suffix == QStringLiteral("mjs") || suffix == QStringLiteral("cjs")) |
| 40 | + { |
| 41 | + return QByteArrayLiteral("text/javascript"); |
| 42 | + } |
| 43 | + |
| 44 | + return QByteArrayLiteral("application/octet-stream"); |
| 45 | +} |
| 46 | +} |
| 47 | + |
17 | 48 | StaticFileServing::StaticFileServing (QObject * parent) |
18 | 49 | : QObject (parent) |
19 | 50 | , _baseUrl () |
@@ -133,25 +164,16 @@ void StaticFileServing::onRequestNeedsReply (QtHttpRequest * request, QtHttpRepl |
133 | 164 | QFile file(_baseUrl % "/" % path); |
134 | 165 | if (file.exists()) |
135 | 166 | { |
136 | | - QMimeType mime = _mimeDb->mimeTypeForFile (file.fileName ()); |
137 | | - if (file.open (QFile::ReadOnly)) { |
138 | | - QByteArray data = file.readAll (); |
139 | | - |
140 | | - // Workaround https://bugreports.qt.io/browse/QTBUG-97392 |
141 | | - if (mime.name() == QStringLiteral("application/x-extension-html")) |
142 | | - { |
143 | | - reply->addHeader ("Content-Type", "text/html"); |
144 | | - } |
145 | | - else |
146 | | - { |
147 | | - reply->addHeader ("Content-Type", mime.name().toLocal8Bit()); |
148 | | - } |
149 | | - reply->appendRawData (data); |
150 | | - file.close (); |
| 167 | + if (file.open(QFile::ReadOnly)) |
| 168 | + { |
| 169 | + QByteArray data = file.readAll(); |
| 170 | + reply->addHeader("Content-Type", resolveMimeType(file.fileName(), _mimeDb)); |
| 171 | + reply->appendRawData(data); |
| 172 | + file.close(); |
151 | 173 | } |
152 | 174 | else |
153 | 175 | { |
154 | | - printErrorToReply (reply, QtHttpReply::Forbidden ,"Requested file: " % path); |
| 176 | + printErrorToReply(reply, QtHttpReply::Forbidden, "Requested file: " % path); |
155 | 177 | } |
156 | 178 | } |
157 | 179 | else |
|
0 commit comments