How to convert binary files to String securely?

1

Operating System: Windows 10;

Ruby Version: 2.2.1;

Server Application: Apache 2 (mod_cgi);

I should create a script that reads a file, converts it to text, and after a possible processing, send the result to the user.

The current process works very well for text files (html, plain, css etc ...), but when the subject is binaries (pdf, jpg, png etc ...) the files always leave "unreadable" or corrupted (in the case of JPEGs) since the browser can mount the image but it is not the original on the server.

The code used so far is as follows:

mime_type = 'image/jpeg'
file = File.open(File.dirname(__FILE__) + 'imagem.jpg', "rb")
head = "Status: 200 OK\nContent-Type: #{mime_type}\nConnection: close\nContent-Length: #{file.size()}\n\n"
body = file.read()
print head + body

Does anyone know a safe way to read binary files in Windows to return to the client?

    
asked by anonymous 25.08.2015 / 03:37

1 answer

0
puts puts a CR / LF at the end of each line, as you were not specifying the size of the binary in the header the other side is accepting those two bytes as part of the content, which obviously corrupts it. Use "print" instead of puts.

    
26.08.2015 / 06:27