9

I use ruby 1.9.3 and redmine 1.4.4

According to this -> Please help me send a jpg file using send_data , I do that in a controller:

  @file = temp.path
  File.open(@file, 'r') do |f|
    send_data f.read, :filename => "myfile.pdf", :type => "application/pdf", :disposition => "attachment"
  end
  File.delete(@file)

But it returns ArgumentError (invalid byte sequence in UTF-8), why ?

Arun Kumar Mohan
  • 11,517
  • 3
  • 23
  • 44
EloHailwidis
  • 403
  • 1
  • 4
  • 16
  • `send_file` doesn't work? – Mischa Apr 15 '14 at 12:43
  • send_file works but I want to do `File.delete(@file)` in the end. I edit my question. – EloHailwidis Apr 15 '14 at 12:46
  • Why can't you send the file with `send_file` and then delete? – Mischa Apr 15 '14 at 12:54
  • because it send me a damage pdf... http://stackoverflow.com/questions/22933871/clean-tmp-when-send-file-is-over – EloHailwidis Apr 15 '14 at 13:01
  • 1
    When using `send_file`, you don't need `File.open do |f|` etc. You can just do `send_file @file, :disposition => "attachment"`. Did you try that? – Mischa Apr 15 '14 at 13:12
  • If I do `send_file temp.path, :disposition => "attachment"` and `File.delete(temp.path)` I have a damage PDF and I can't open it. Same with `temp.close temp.unlink` instead of File.delete. I use send_data because I found this (http://stackoverflow.com/questions/18232088/in-ruby-on-rails-after-send-file-method-delete-the-file-from-server) and the first answer is exacly what I want to do: "You can try using send_data instead, which will block until the data is sent, allowing your File.delete request to succeed". But it doesn't work with me – EloHailwidis Apr 15 '14 at 13:20

1 Answers1

14

The PDF file has to be encoded

 file = temp.path
 File.open(file, 'r') do |f|
   send_data f.read.force_encoding('BINARY'), :filename => filename, :type => "application/pdf", :disposition => "attachment"
 end
 File.delete(file)
EloHailwidis
  • 403
  • 1
  • 4
  • 16