Getting filename before saving in ActiveStorage - Rails 5.2.1

拈花ヽ惹草 提交于 2020-01-25 08:42:25

问题


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?


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/53505722/getting-filename-before-saving-in-activestorage-rails-5-2-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!