braaja
23rd March 2009, 00:29
Hi,
i have to post this solution, because i spent 2 days with founding it.
If you are developing a http service (server), you may be looking for a way, how to send non-text files to browser.
Example: I develop a WMS Server, which sends in some concrete cases an XML file and in the others image with a map. But the question is, how to stream the file to server?!
Solution: You have opened QTcpSocket and now you have to send an image (or any other file) to a server.
QTextStream resultStream(mySocket); // QTcpSocket* mySocket
resultStream.setAutoDetectUnicode(true); // if needed
// Header in each case
resultStream << "HTTP/1.0 200 Ok\r\n";
resultStream << "Content-Type: " + contentType + "\r\n"; // e.g. image/png
resultStream << "\r\n"; // end of header
if (contentType == "text/xml") { // should be extended - text/plain, text/html, ...
resultStream << content;// in this case QDomDocument converted to QString
} else { // maps and other files
QFile transferedFile("file.png");
if (!transferedFile.open(QIODevice::ReadOnly)) {
// handle error
}
resultStream.flush(); // flush buffer with header to the web browser
// Streaming the file
QByteArray block = transferedFile.readAll();
mySocket->write(block);
mySocket->close(); // finished :)
}
Hope it helped at least one person :D
i have to post this solution, because i spent 2 days with founding it.
If you are developing a http service (server), you may be looking for a way, how to send non-text files to browser.
Example: I develop a WMS Server, which sends in some concrete cases an XML file and in the others image with a map. But the question is, how to stream the file to server?!
Solution: You have opened QTcpSocket and now you have to send an image (or any other file) to a server.
QTextStream resultStream(mySocket); // QTcpSocket* mySocket
resultStream.setAutoDetectUnicode(true); // if needed
// Header in each case
resultStream << "HTTP/1.0 200 Ok\r\n";
resultStream << "Content-Type: " + contentType + "\r\n"; // e.g. image/png
resultStream << "\r\n"; // end of header
if (contentType == "text/xml") { // should be extended - text/plain, text/html, ...
resultStream << content;// in this case QDomDocument converted to QString
} else { // maps and other files
QFile transferedFile("file.png");
if (!transferedFile.open(QIODevice::ReadOnly)) {
// handle error
}
resultStream.flush(); // flush buffer with header to the web browser
// Streaming the file
QByteArray block = transferedFile.readAll();
mySocket->write(block);
mySocket->close(); // finished :)
}
Hope it helped at least one person :D