QNetworkRequest下载图片?

时间:2013-08-08 13:09:25

标签: qt

我已经使用QNetworkRequest从网上检索xml而没有任何问题:

request.setUrl(QUrl("http://api.somesite.com/api/4we35r/somefile.xml"));

myNetworkAccessManager->get(request);

我如何下载图片?例如:

http://www.mysite.com/27eye28/images/myimage.png

我只是用png url替换上面的xml url吗?我必须做些什么特别的事吗?

1 个答案:

答案 0 :(得分:2)

是的,您只需更换网址即可。

这是一个有效的例子,

void MainWindow::GetImage(QString url)
{
    QNetworkAccessManager* manager = new QNetworkAccessManager(this);
    connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(replyFinished(QNetworkReply *)));

    QUrl url = QUrl(url);

    QNetworkRequest request(url);

    manager->get(request);
}

void MainWindow::replyFinished(QNetworkReply *reply)
{
    if(reply->error() != QNetworkReply::NoError)
    {
        ui->textBrowser->setText("Error: " +  reply->errorString());
    }
    else
    {
        QByteArray responseData = reply->readAll();
        QFile file("d:\\myImage.png");
        file.open(QIODevice::WriteOnly);
        file.write((responseData));
        file.close();
    }
}