使用c++和Qt下载二进制文件


Downloading a binary file using c++ and Qt

我想从php脚本下载一个*.exe文件并执行它。

下载文件后,我就可以再执行它了。当我查看文件内部时,里面有很多问号

PHP脚本:

header('Content-Description: File Transfer');
header('Content-Type: application/x-download');
header('Content-Disposition: attachment; filename='.basename($file_name));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file_name));
ob_clean();
flush();
readfile($file_name);
exit;

C++:

 QFile offline_ip_adress_calculator(QDir::currentPath() + "/offline_ip_adress_calculator.exe");
    //Check if the File exists and clear its content
    if(!offline_ip_adress_calculator.open(QFile::ReadWrite | QIODevice::Truncate))
    {
        msgBox.critical(this, "I/O error", "Can't open offline_ip_adress_calculator.exe for update");
        return;
    }
    QDataStream text_stream(&offline_ip_adress_calculator);
    while(reply->size() > 0)
    {
        QByteArray replystring = reply->read(2048);
        text_stream << replystring;
    }
    offline_ip_adress_calculator.close();

回复是一个"QNetworkReply"

问题是将二进制数据视为文本。

使用QDataStream::operator<<时,来自replystring的数据将像字符串一样处理。但它不是文本字符串,只是一系列字节。

使用QNetworkReply::readQFile::write:

char buffer[2048];
qint64 size = reply->read(buffer, sizeof(buffer));
offline_ip_adress_calculator.write(buffer, size);

这里有更清晰纯粹的Qt解决方案:

   QByteArray downloadedData = reply->readAll();
   QFile file("somefile");
   file.open(QIODevice::ReadWrite);
   file.write(downloadedData.data(),downloadedData.size());
   file.close();

我尝试过@someProgrammaberDude的解决方案。我用这种方式下载了一个png文件,只得到了图像的上半部分,并不奇怪,文件大小正好是2048或我设置的任何数字。