4
    QNetworkAccessManager *nam = new QNetworkAccessManager();
    QUrl url2("ftp://127.0.0.1/test.txt/");
    url2.setPassword("12345");
    url2.setUserName("user");
    QNetworkRequest req(url2);


   QNetworkReply *reply = nam->get(req);
   QByteArray data = reply->readAll() ;
   qDebug() << data ;

It connects to the local ftp server and reads the file but it gets garbage what am I doing wrong??

user2584587
  • 133
  • 2
  • 10
  • http://stackoverflow.com/questions/14111120/qt-code-to-get-list-of-files-from-ftp-server-using-qnetworkaccessmanager - I haven't heard exactly when they'll get to it either – Son-Huy Pham Jul 15 '13 at 18:22

1 Answers1

5

get() doesn't perform the GET request right away synchronously, but just creates a QNetworkReply object, where the actual request will be performed asynchronously at a later point.

readAll() reads only the data available at a given time but doesn't block to wait for more data. Right after creation, there isn't any data available.

To wait for all data to be downloaded, connect to the finished() and error() signals:

connect(reply, SIGNAL(finished()), this, SLOT(requestFinished()));
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(requestError(QNetworkReply::NetworkError));

In the requestFinished() slot you can then use readAll(). That works ok when downloaing small files only. When downloading larger files, better connect to the readyRead() signal and handle the arriving data in incremental chunks instead of using a single readAll() in the very end.

Frank Osterfeld
  • 24,815
  • 5
  • 58
  • 70
  • But I'm doing this in main in a simple console app I don't have any classes with slots and signals how would I connect those? – user2584587 Jul 15 '13 at 19:30
  • I would introduce such class(es) then. The alternative are local event loops, the root of many evils. – Frank Osterfeld Jul 15 '13 at 21:44
  • I made the class and connected the slot and signal to the object like you told me but I still get garbage when I read the file what am I doing wrong? - -I get this for output --------> """" – user2584587 Jul 16 '13 at 12:49
  • I got it to work I checked the error message and aparently it was a permissions issue with the file. – user2584587 Jul 16 '13 at 19:05