关键方法如下:
QNetworkAccessManager *downloadManager;
QNetworkReply* reply;
QNetworkRequest* request=new QNetworkRequest(url);//url就是下载网址
reply = downloadManager->get(*request);
QString str = reply->rawHeader("Content-Disposition");
qDebug() << "str: " << str;
QString patternStart = "filename=\".*\"";//正则表达式匹配
QRegExp expStart(patternStart);
int startindex = str.indexOf(expStart);
QString newString =str.right(str.size()-startindex);
QStringList newStringList = newString.split("\"");//用"来分割
QString fileName =newStringList.at(1);
str一般是 "attachment; filename="文件名及后缀"",但也可能以后会变,为了使程序具有一般性,通过匹配filename="******",找到当前位置,从而获取到当前位置之后的内容,然后用上引号“分割,获取到文件名。
其他方法:
1、来自qt实例代码
QString localFile = url.toLocalFile();
QString fileName = QFileInfo(localFile).fileName();容易出问题,不准确
2、来自http://stackoverflow.com/questions/13766748/downloadprogress-and-finished-signals-not-being-emitted
QString str = reply->rawHeader("Content-Disposition"); QString end = str.mid(21); end.chop(1); qDebug() << "File name: " << end; qDebug() << "File type: " << reply->rawHeader("Content-Type"); qDebug() << "File size (bytes): " << reply->bytesAvailable(); QString defaultFileName = QFileInfo(end).fileName(); QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), defaultFileName); if (fileName.isEmpty()) return; file = new QFile(fileName);
这种方法是根据位置截取,但当内容变化时,会出错,通用性不强,不过我的方法从这里借鉴来。