簡體   English   中英

使用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();

我嘗試了@SomeProgrammerDude的解決方案。我以這種方式下載了png文件,只得到了圖像的上半部分,而且文件大小恰好是2048或我設置的任何數字,這並不奇怪。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM