# Net/http and binary files

**URL:** <https://www.ruby-forum.com/t/net-http-and-binary-files/114180>\
**Category:** Ruby\
**Created:** [September 9, 2007, 7:11am UTC](https://www.ruby-forum.com/t/net-http-and-binary-files/114180 "2007-09-09T07:11:45Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![costi](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/4491bb/32.png) [@costi](https://www.ruby-forum.com/u/costi)\
**Post date:** [September 9, 2007, 7:11am UTC](https://www.ruby-forum.com/t/net-http-and-binary-files/114180/1 "2007-09-09T07:11:45Z")

</div>

I’m using the code from the example  
[http://www.ruby-doc.org/stdlib/libdoc/net/http/rdoc/index.html](http://www.ruby-doc.org/stdlib/libdoc/net/http/rdoc/index.html) for the  
http/net library:

```
File.open('result.txt', 'w') {|f|
  http.get('/~foo/') do |str|
    f.write str
  end
}

```

This works fine for html files. But for binary files the result is a  
corrupted file.  
I’ve run this in the console:

> > Net::HTTP.start(‘localhost’, 80){|http|File.open(‘result.mp3’, ‘w’){|f|http.g  
> > et(‘/crocodil2/adrian.mp3’) {|str|f.write str}}}  
> > =\> #\<Net::HTTPOK 200 OK readbody=true\>

The mp3 files is corrupted. It does not seem to be base64 encoded…  
help please.

---

<div class="post-metadata">

**Author:** ![costi](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/4491bb/32.png) [@costi](https://www.ruby-forum.com/u/costi)\
**Post date:** [September 9, 2007, 7:46am UTC](https://www.ruby-forum.com/t/net-http-and-binary-files/114180/2 "2007-09-09T07:46:29Z")

</div>

Constantin G. wrote:

> I’m using the code from the example  
> [http://www.ruby-doc.org/stdlib/libdoc/net/http/rdoc/index.html](http://www.ruby-doc.org/stdlib/libdoc/net/http/rdoc/index.html)  
> This works fine for html files. But for binary files the result is a  
> corrupted file.  
> I’ve run this in the console:
> 
> > > Net::HTTP.start(‘localhost’, 80){|http|File.open(‘result.mp3’, ‘w’){|f|http.g  
> > > et(‘/crocodil2/adrian.mp3’) {|str|f.write str}}}  
> > > =\> #\<Net::HTTPOK 200 OK readbody=true\>  
> > > The mp3 files is corrupted. It does not seem to be base64 encoded…  
> > > help please.

The example works on \*nix systems, but on Windoze, you must write the  
file in binary mode: File.open(‘result.mp3’, ‘wb’)

Clifford H…

---

<div class="post-metadata">

**Author:** ![costi](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/4491bb/32.png) [@costi](https://www.ruby-forum.com/u/costi)\
**Post date:** [September 10, 2007, 12:25am UTC](https://www.ruby-forum.com/t/net-http-and-binary-files/114180/3 "2007-09-10T00:25:01Z")

</div>

Clifford H. wrote:

> The example works on \*nix systems, but on Windoze, you must write the  
> file in binary mode: File.open(‘result.mp3’, ‘wb’)

Wonderful. Forgot about that… Thank you.
