1

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

但是,当我一次多次调用此方法时(例如遍历 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)+"\"}");
}
4

1 回答 1

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!!!!
}
于 2013-08-24T12:07:31.533 回答