QNetworkAccessManager多次上载失败



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

但是,当我一次多次调用这个方法时(比如迭代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)+""}");
}

首先,不要每次开始上传时都创建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!!!!
}

相关内容

  • 没有找到相关文章

最新更新