PDA

View Full Version : Streaming files to web browser using QTcpSocket



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

kotodama
22nd May 2010, 15:08
Thanks A LOT! I subscribed to this forum just to say Thank you, and it seems that I'll hang out here more often. Again thanks :)

sana
5th February 2011, 13:15
thanks a lot this is a g8t help ;)but i want to know how do u stream an audio file from the web browser...please help....:confused:
thank u in advance

kazuko
29th July 2014, 20:30
Thank you !! You have saved my day :D