File attachment tag

back edit

#file_attachment_tag

Generate file attachment fields with file_attachment_tag.

<%= file_attachment_tag(model: :assets, class: "position-relative is-default") do %>
  <textarea rows="4" class="width-full form-control rounded-bottom-0"></textarea>
  <label class="drag-and-drop text-normal d-block">
    <input type="file" class="js-manual-file-chooser sr-only show-on-focus bg-gray" multiple>
    <span class="default">Choose, paste, or drop in an image.</span>
    <span class="loading">Uploading...</span>
    <span class="error failed-request">Upload failed.</span>
  </label>
<% end %>

This generates the following markup:

<file-attachment
  class="position-relative is-default"
  data-upload-policy-url="/user_policies"
  data-upload-policy-authenticity-token="token">
  <input type="hidden" value="..." class="js-data-upload-policy-url-csrf" name="csrf">
  <textarea rows="4" class="width-full form-control rounded-bottom-0"></textarea>
  <label class="drag-and-drop text-normal d-block">
    <input type="file" class="js-manual-file-chooser sr-only show-on-focus bg-gray" multiple>
    <span class="default">Choose, paste, or drop in an image.</span>
    <span class="loading">Uploading...</span>
    <span class="error failed-request">Upload failed.</span>
  </label>
</file-attachment>

Use upload events to update the UI:

document.addEventListener('upload:complete', function(event) {
  const textarea = event.target.querySelector('textarea')
  textarea.value = `'${event.detail.attachment.file.name}' uploaded successfully.\n` + (textarea.value || '')
  textarea.focus()
})