ruby – How to convert binary files to String securely?

Question:

Operating System: Windows 10;

Ruby Version: 2.2.1;

Server Application: Apache 2 (mod_cgi);

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

The current process works very well for text files (html, plain, css etc…), but when it comes to binaries (pdf, jpg, png etc…) the files always come out "unreadable" or corrupted (no case of JPEGs), since the browser is able to 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 on Windows to return to the client?

Answer:

"puts" adds a CR/LF at the end of each line, as you weren't specifying the binary size in the header the other side is accepting these two extra bytes as part of the content, which obviously corrupts it. Use "print" instead of puts.

Scroll to Top
AllEscort