sinatra icon indicating copy to clipboard operation
sinatra copied to clipboard

Can't read a file from an input type='file' tag in chunks.

Open kektre opened this issue 16 years ago • 7 comments

In sinatra 1.0 a file read (from an input type='file' name='f'' tag) and saved this way works fine.

 File.open(path, "w") do |buff|
   while blk = params[:f][:tempfile].read(65536)
     buff.write(blk)
   end
end

In sinatra 1.1 master this doesn't work (the created file is empty). Only possible way is to use: File.read(params[:f][:tempfile])

kektre avatar Oct 17 '10 16:10 kektre

Are you running both on the same rack version?

rkh avatar Oct 17 '10 16:10 rkh

Rack version 1.2.1, Ruby 1.9.2

kektre avatar Oct 17 '10 18:10 kektre

Thanks, will look into this.

rkh avatar Oct 17 '10 19:10 rkh

Hi, I think I've found where the problem is ohhgabriel@509599bcd3ca2723e26648361b236069a77920ac

gnandretta avatar Oct 18 '10 03:10 gnandretta

with the patch above I am getting: Encoding::UndefinedConversionError: "\xFF" from ASCII-8BIT to UTF-8 exception when writing in chunks

edit: when using the "wb" flag for File.open, with the patch applied it saves files correctly. Although this is kind of weird, because I am on linux and the "b" flag is windows specific only afaik(?).

kektre avatar Oct 18 '10 08:10 kektre

Yeah, the input stream is ASCII-8BIT but you're trying to write to a file in unicode, "wb" sets encoding to binary in 1.9. This is not related to your OS. Even though your OS/file system might not care, 1.9 is encoding aware.

rkh avatar Oct 18 '10 10:10 rkh

Merged ohhgabriel's fix (thanks). Dealing with the encoding in this case has either to be done on application layer, or if it can be detected from the incoming request, at rack layer. Depending on the type of upload, you should just stick with "wb" and eventually handle encoding later.

rkh avatar Oct 18 '10 10:10 rkh