# Handling binary files with mod\_ruby and cgi

**URL:** <https://www.ruby-forum.com/t/handling-binary-files-with-mod-ruby-and-cgi/124861>\
**Category:** Ruby\
**Created:** [January 3, 2008, 7:51am UTC](https://www.ruby-forum.com/t/handling-binary-files-with-mod-ruby-and-cgi/124861 "2008-01-03T07:51:12Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [January 3, 2008, 7:51am UTC](https://www.ruby-forum.com/t/handling-binary-files-with-mod-ruby-and-cgi/124861/1 "2008-01-03T07:51:12Z")

</div>

I’m trying to write a CGI script that will fetch a named file and send  
it back to the browser. No matter what output method I use, it’s  
writing two newlines to the end of the file, which corrupts many  
binary file formats. I’m sure I’m missing something obvious. Here’s a  
simple version of the script (yes, I’m aware it can be used to read  
any file on the system - the full version sanitizes the filename and  
restricts access to a specific directory):

require ‘mime/types’  
cgi = CGI.new()  
file = cgi[‘file’].untaint  
mimetype = MIME::Types.type\_for(file)[0]  
cgi.header(mimetype.nil? ? “application/octet-stream” :  
mimetype.simplified)  
write File.read(‘file’)
