2013-08-01 59 views
2

我想從php腳本下載* .exe文件並執行它。使用C++和Qt下載二進制文件

當我下載文件後,我可以'執行它了。當我查看文件時,其中有很多問號。

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」

回答

2

的問題是,你把二進制數據作爲文本。

當您使用QDataStream::operator<<時,來自replystring的數據將像字符串一樣處理。但它不是文本字符串,只是一系列字節。

而是使用QNetworkReply::readQFile::write

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

哇,太簡單了。它的工作原理:) – user2357505

+0

你是如何選擇緩衝區爲2048?如果文件大於2018字節會發生什麼情況? –

+1

@MuhammetAliAsan 2048在計算機方面是一個不錯的數字(2的倍數)。如果有更多的數據要讀取,它只需要兩個(或更多)迭代來讀取/寫入所有數據。 –

2

這裏更加清晰純淨的Qt解決方案:

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

我已經試過@ SomeProgrammerDude的solution.I下載的PNG文件那樣,只得到了圖像的上半部分,並且不奇怪,文件大小恰好是2048或我設置的任何數字。