我想你想通过HTTP下载文件。这里是你可以做什么:
- 在你* .pro文件中添加
QT += network
- 创建QNetworkAccessManager类的实例;
- 供应文件URL通过QNetworkRequest对象:
manager->get(QNetworkRequest("file_url"));
- 连接到的QNetworkAccessManager
- 的finished信号在完成信号处理程序读取QNetworkReply的内容,并将其保存到本地文件。
下面是一个小例子。下载将在MainForm类的按钮,点击开始:
mainwindow.h:
#include <QMainWindow>
#include <QNetworkAccessManager>
#include <QDebug>
#include <QUrl>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QFile>
#include <QFileInfo>
#include <QPushButton>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
QNetworkAccessManager* _manager;
private slots:
void on_pushButton_clicked();
void downloadFinished(QNetworkReply *reply);
};
mainwindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QPushButton* button = new QPushButton("Download", this);
button->setGeometry(20, 20, 80, 30);
connect(button, SIGNAL(clicked()), SLOT(on_pushButton_clicked()));
_manager = new QNetworkAccessManager(this);
connect(_manager, SIGNAL(finished(QNetworkReply*)), SLOT(downloadFinished(QNetworkReply*)));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
QUrl url("http://pics.mtii.com/ClassPictures2011/MIA/E110227-PMIA3-JEAN/thumbnails/P2270448%20copy.jpg");
_manager->get(QNetworkRequest(url));
}
void MainWindow::downloadFinished(QNetworkReply *reply)
{
QUrl url = reply->url();
if (reply->error())
{
qDebug() << "Download of " << url.toEncoded().constData()
<< " failed: " << reply->errorString();
}
else
{
QString path = url.path();
QString fileName = QFileInfo(path).fileName();
if (fileName.isEmpty()) fileName = "download";
QFile file(fileName);
if (file.open(QIODevice::WriteOnly))
{
file.write(reply->readAll());
file.close();
}
qDebug() << "Download of " << url.toEncoded().constData()
<< " succeded saved to: " << fileName;
}
}
希望这会有所帮助,至于
它的值文件? – RedX
下载在linedit中输入的文件,并将值传递给字符串...谢谢 – Vamsi