2011-03-08 50 views
0

我想下载在线编辑部件中输入的网址。qt networkManager获取

我不能得到它的工作,有人可以给我一个简短的代码片段,它可以把文件的值到QString?

void imdb::on_imdbGetButton_clicked() 
{ 

Qstring link1 = ui->lineEdit2->text(); 
// QString link1 is the url to be downloaded. 
} 

我加入,所需要的头文件..

谢谢..

+0

它的值文件? – RedX

+0

下载在linedit中输入的文件,并将值传递给字符串...谢谢 – Vamsi

回答

1

我想你想通过HTTP下载文件。这里是你可以做什么:

  1. 在你* .pro文件中添加QT += network
  2. 创建QNetworkAccessManager类的实例;
  3. 供应文件URL通过QNetworkRequest对象:manager->get(QNetworkRequest("file_url"));
  4. 连接到的QNetworkAccessManager
  5. 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; 
    } 
} 

希望这会有所帮助,至于