QNetworkAccessManager多次上传失败

时间:2013-08-18 14:50:46

标签: c++ qt qt5 qnetworkaccessmanager qnetworkrequest

在我的应用程序中,我有一种方法将文件上传到服务器,这很好用。

但是当我一次多次调用此方法时(比如遍历chooseFilesDialog的结果),前7个(或多或少)文件正确上传,其他文件永远不会上传。

我认为这必须与服务器不允许来自同一来源的X连接的事实相关联?

如何确保上传等待免费的已建立连接?

这是我的方法:

QString Api::FTPUpload(QString origin, QString destination)
{
    qint64 timestamp = QDateTime::currentMSecsSinceEpoch();
    QUrl url("ftp://ftp."+getLSPro("domain")+destination);
    url.setUserName(getLSPro("user"));
    url.setPassword(getLSPro("pwd"));

    QFile *data = new QFile(origin, this);
    if (data->open(QIODevice::ReadOnly))
    {
        QNetworkAccessManager *nam = new QNetworkAccessManager();
        QNetworkReply *reply = nam->put(QNetworkRequest(url), data);
        reply->setObjectName(QString::number(timestamp));
        connect(reply, SIGNAL(uploadProgress(qint64, qint64)), SLOT(uploadProgress(qint64, qint64)));

        return QString::number(timestamp);
    }
    else
    {
        qDebug() << "Could not open file to FTP";
        return 0;
    }
}

void Api::uploadProgress(qint64 done, qint64 total) {
    QNetworkReply *reply = (QNetworkReply*)sender();
    emit broadCast("uploadProgress","{\"ref\":\""+reply->objectName()+"\" , \"done\":\""+QString::number(done)+"\", \"total\":\""+QString::number(total)+"\"}");
}

1 个答案:

答案 0 :(得分:0)

首先,每次开始上传时都不要创建QNetworkManager 其次,您必须删除new()的所有内容,否则会留下内存泄漏。这包括QFileQNetworkManagerQNetworkReply(!) 第三,你必须等待finished()信号。

Api::Api() {  //in the constructor create the network access manager
    nam = new QNetworkAccessManager()
    QObject::connect(nam, SIGNAL(finished(QNetworkReply*)), this, SLOT(finished(QNetworkReply*)));
}

Api::~Api() {  //in the destructor delete the allocated object
    delete nam;
}

bool Api::ftpUpload(QString origin, QString destination) {
    qint64 timestamp = QDateTime::currentMSecsSinceEpoch();
    QUrl url("ftp://ftp."+getLSPro("domain")+destination);
    url.setUserName(getLSPro("user"));
    url.setPassword(getLSPro("pwd"));

    //no allocation of the file object;
    //will automatically be destroyed when going out of scope
    //I use readAll() (see further) to fetch the data
    //this is OK, as long as the files are not too big
    //If they are, you should allocate the QFile object
    //and destroy it when the request is finished
    //So, you would need to implement some bookkeeping,
    //which I left out here for simplicity
    QFile file(origin);
    if (file.open(QIODevice::ReadOnly)) {
        QByteArray data = file.readAll();   //Okay, if your files are not too big
        nam->put(QNetworkRequest(url), data);
        return true;

        //the finished() signal will be emitted when this request is finished
        //now you can go on, and start another request
    }
    else {
      return false;
    }
}

void Api::finished(QNetworkReply *reply) {
    reply->deleteLater();  //important!!!!
}