Joern Akkermann
Joern Akkermann

Reputation: 3622

Rails/Ruby: uploading a binary File and writing it with a File-Object

I need to upload Word and Excel files on my site.

I create a upload form, upload the file and save it like this:

f = File.new("public/files/#{user.id.to_s}/filename", "w+")
f.write params[:file].read
f.close

Word and Excel files must be saved as binary data.

Sadly the Filemode "b" is only for windows and I'm under linux.

What to do?

Yours,

Joern

Upvotes: 3

Views: 4212

Answers (1)

Ion Br.
Ion Br.

Reputation: 2648

Binary file mode "b" may appear with any of the key letters (r, r+, w, w+, a, a+) so you can do it like this f = File.new("public/files/#{user.id.to_s}/filename", "w+b").

And the "b" mode is not only for windows. Ruby documentation says that "Binary file mode (may appear with any of the key letters r, r+, w, w+, a, a+. Suppresses EOL <-> CRLF conversion on Windows. And sets external encoding to ASCII-8BIT unless explicitly specified." and says nothing about "b" being just for windows. It just tells that it works different on windows/linux with line endings. So you can use "w+b" mode on linux and windows.

Upvotes: 5

Related Questions