这是一个有问题的版本:
class download_file :public QObject{
Q_OBJECT;
public:
download_file(QString url, QString path);
void sendRequest();
public slots:
void requestFinished(QNetworkReply* reply);
protected:
QNetworkAccessManager* httpMgr;
private:
QString url, path;
};
download_file::download_file(QString url,QString path)
{
this->url = url;
this->path = path;
}
void download_file::sendRequest()
{
httpMgr = new QNetworkAccessManager(this);
QObject::connect(httpMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(requestFinished(QNetworkReply*)));
QNetworkRequest requestInfo;
requestInfo.setUrl(QUrl(url));
QNetworkReply *reply = httpMgr->get(requestInfo);
}
void download_file::requestFinished(QNetworkReply* reply)
{
QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
if (statusCode.isValid())
qDebug() << "status code=" << statusCode.toInt();
QVariant reason = reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
if (reason.isValid())
qDebug() << "reason=" << reason.toString();
QNetworkReply::NetworkError err = reply->error();
if (err != QNetworkReply::NoError) {
qDebug() << "Failed: " << reply->errorString();
}
else {
// 获取返回内容
QByteArray ba(reply->readAll());
//qDebug() << ba;
//保存
QFile file(path);
bool ok = file.open(QIODevice::WriteOnly);
if(ok){
file.write(ba);
file.close();
}
else {
qDebug() << "open failed!";
}
}
}
当要下载的文件过大时,程序会崩溃!!!(std::bad_alloc)(所以只可以下载一些小的文件)
我认为这是ba(QByteArray)太大了,要一下子往文件中写入太多的数据,导致new失败了。
修复:文章来源:https://www.toymoban.com/news/detail-799914.html
Qt 基于http的网络文件下载_qt http下载文件-CSDN博客(参考+引用)文章来源地址https://www.toymoban.com/news/detail-799914.html
class download_file :public QObject{
Q_OBJECT;
public:
download_file(QString url, QString path);
void sendRequest();
public slots:
void on_finished();
void on_readyRead();
void on_downloadProgress(qint64 bytesRead, qint64 totalBytes);
protected:
QNetworkAccessManager* httpMgr;
private:
QString url, path;
QFile* file;
QNetworkReply* reply;
};
download_file::download_file(QString url,QString path)
{
this->url = url;
this->path = path;
}
void download_file::sendRequest()
{
httpMgr = new QNetworkAccessManager(this);
QNetworkRequest requestInfo;
requestInfo.setUrl(QUrl(url));
PRINTF_LOCATION() << url;
reply = httpMgr->get(requestInfo);
connect(reply, &QNetworkReply::finished, this, &download_file::on_finished);
connect(reply, &QNetworkReply::readyRead, this, &download_file::on_readyRead);
connect(reply, &QNetworkReply::downloadProgress, this, &download_file::on_downloadProgress);
file = new QFile(path);
if (!file->open(QIODevice::WriteOnly))
return;
}
void download_file::on_finished()
{
file->close();
delete file;
file = nullptr;
reply->deleteLater();
reply = nullptr;
}
void download_file::on_downloadProgress(qint64 bytesRead, qint64 totalBytes)
{
qDebug() << bytesRead << " " << totalBytes;
}
void download_file::on_readyRead()
{
file->write(reply->readAll());
}
到了这里,关于Qt下载http文件的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!