How to download binary file using wxwidgets

1.1k views Asked by At

I found this code snippet for downloading file:

wxURL url(wxT("http://www.example.com/file.txt"));
if(url.GetError()==wxURL_NOERR)
{
    wxString htmldata;
    wxInputStream *in = url.GetInputStream();

    if(in && in->IsOk())
    {
        wxStringOutputStream html_stream(&htmldata);
        in->Read(html_stream);
        wxLogMessage(htmldata);
    }
    delete in;
}

But fistly it just logs content of file and only for text-files. But I need to download *.exe file to execute it later. So I need to adapt this code to work with binary data, and save this data to file on the disk. Too many Streams used here for my understanding what's going on here. Please help.

1

There are 1 answers

0
hiropon On

I have written below code previously... This will work fine to download binary files in any platforms.

 /** START */
 // ex) ht tp://mysite.com/mypath.jpg
 wxString path   = wxT("/mypath.jpg");
 wxString server = wxT("mysite.com");

 wxHTTP http; 
 http.SetHeader(_T("Content-type"), contentType); 
 http.SetTimeout(10);

 // wxString imageFilePath = wxT("/tmp/image.jpg");
 wxFileOutputStream output(imageFilePath);
 wxDataOutputStream store(output);

 if (http.Connect(server, 80)) 
 {
  wxInputStream *stream;
  stream = http.GetInputStream(path);

  if (stream == NULL) 
  {
       output.Close();
  } 
  else 
  {
       unsigned char buffer[1024];
       int byteRead;

       // receive stream
       while (!stream->Eof()) 
       {
        stream->Read(buffer, sizeof(buffer));
        store.Write8(buffer, sizeof(buffer));
        byteRead = stream->LastRead();
        if (byteRead <= 0) 
        {
         break;
        }
       }

       output.Close();
  }
 } 
 else 
 {
  output.Close();
 }