8

I am trying to get the name of the file uploaded by a user before ActiveStorage goes on to save it. The form is generated using form_with and is shown below:

<%= form_with model: upload do |form| %>
  <div class="">
    <%= form.file_field :files, multiple: true, direct_upload: true, required: true %>
    <%= form.label :files, '', class: 'icon ion-ios-cloud-upload' do %>
      <span>click the icon to select files</span>
    <% end %>

    <div class="actions">
      <%= form.submit "Upload", class: "btn btn-primary" %>
    </div>
 </div>
<% end %>

I have tried accessing params[:upload][files] and calling .original_filename on it as described here but I get the error NoMethodError: undefined method `original_filename' for #<String:0x007fac77fd18c8>.

The file does come back as a string when I inspect the params, so how do I get the filename or how do I get original_filename to work?

troy34
  • 335
  • 1
  • 4
  • 10
  • `original_filename` is one of the attributes of `ActionDispatch::Http::UploadedFile` not `ActiveStorage::Blob` https://api.rubyonrails.org/classes/ActionDispatch/Http/UploadedFile.html https://guides.rubyonrails.org/form_helpers.html#what-gets-uploaded https://api.rubyonrails.org/classes/ActiveStorage/Blob.html#method-i-filename – kangkyu Aug 27 '22 at 06:09

3 Answers3

13

I was finally able to get the file name by doing file.blob.filename after the file had been attached.

troy34
  • 335
  • 1
  • 4
  • 10
  • 1
    Did you need `.blob`? I didn't need it, and it didn't appear to make a difference for me. Is there some benefit? – iconoclast Jun 06 '20 at 02:44
10

Based on the ActiveStorage documentation, I found this worked for me:

file.filename.to_s

In my case I have a model with

has_one_attached :file

OP's situation is slightly different and your situation may differ too, so adjust accordingly.

Troy's solution did not work for me as-is. I had to add the .to_s to get the file name instead of an ActiveStorage::Filename object. But I'm not sure why he's using .blob in there. I didn't need it, but perhaps there's a good reason.

iconoclast
  • 21,213
  • 15
  • 102
  • 138
-1

You need to add multipart: true to your form.

https://guides.rubyonrails.org/form_helpers.html#uploading-files

The other thing is that if you have multiple files you'll have multiple filenames.

params[:upload][files].each do |file|
  file.original_filename
end
luisenrike
  • 2,742
  • 17
  • 23
  • ```form_with``` already adds that, but I have tried adding `multipart: true` to the form and it doesn't work – troy34 Nov 27 '18 at 19:39