I can post a file in Qt using QNetworkReply
, QNetworkAccessManager
, QNetworkRequest
, etc. to a server. This server converts the file and spits it back. How do I get that spitted-back file? Do I need to find the url of the file coming back from the headers somehow and then have QNetworkAccessManager
make a get request for it? Or can I somehow get it from the existingQNetworkReply
signals and write it to file?
If the server returns the file in response to the request then you can read the file directly from the returned reply :
QNetworkAccessManager nam;
QUrl url(QString("http://www.example.com"));
url.addQueryItem("parameter", "value");
QNetworkRequest request(url);
QNetworkReply *reply = nam.get(request);
QEventLoop eventloop;
connect(reply,SIGNAL(finished()),&eventloop,SLOT(quit()));
eventloop.exec();
if (reply->error() == QNetworkReply::NoError)
{
QByteArray bts = reply->readAll();
QFile file("path/to/file");
file.open(QIODevice::WriteOnly);
file.write(bts);
file.close();
}
You can also do it in an asynchronous way by connecting the finished
signal of the QNetworkAccessManager
to a slot and write the file there :
connect(&nam,SIGNAL(finished(QNetworkReply*)),this,SLOT(onFinished(QNetworkReply*)));
void onFinished(QNetworkReply* reply)
{
if (reply->error() == QNetworkReply::NoError)
{
QByteArray bts = reply->readAll();
QFile file("path/to/file");
file.open(QIODevice::WriteOnly);
file.write(bts);
file.close();
}
}