提问人:Ryzal Yusoff 提问时间:10/1/2018 更新时间:6/21/2020 访问量:2950
使用 “remote:true” 时不显示 Rails Activestorage + DirectUpload javascript 进度条
Rails Activestorage + DirectUpload javascript progress bar not showing when using "remote:true"
问:
我一直在我的 Rails 应用程序中使用 Rails ActiveStorage DirectUpload。这是表单的代码:
<h3>Select Files To Upload</h3>
<%= form_for @uploader, url: uploaders_file_path(@uploader), :html => {:multipart => true} do |f| %>
<%= f.file_field :file, direct_upload: true, class: "form-control" %>
<%= f.button type: "submit", id: "submit-uploader", class: "btn btn-primary btn-md", data: {disable_with: "Uploading..."} do %>
Upload
<% end %>
<% end %>
一切正常,当我上传文件时,进度条也会显示:
但是,当我尝试将表单作为 js 提交时,即使文件上传成功,进度条也不会显示。我只是添加了“remote: true”以使表单作为js提交。但现在进度条不再显示。
下面是表单的新代码:
<%= form_for @uploader, url: uploaders_file_path(@uploader), remote: true, :html => {:multipart => true} do |f| %>
<%= f.file_field :file, direct_upload: true, class: "form-control" %>
<%= f.button type: "submit", id: "submit-uploader", class: "btn btn-primary btn-md", data: {disable_with: "Uploading..."} do %>
Upload
<% end %>
<% end %>
下面是代码:direct_uploads.js
addEventListener("direct-upload:initialize", event => {
const { target, detail } = event
const { id, file } = detail
target.insertAdjacentHTML("beforebegin", `
<div id="direct-upload-${id}" class="direct-upload direct-upload--pending">
<div id="direct-upload-progress-${id}" class="direct-upload__progress" style="width: 0%"></div>
<span class="direct-upload__filename">${file.name}</span>
</div>
`)
})
addEventListener("direct-upload:start", event => {
const { id } = event.detail
const element = document.getElementById(`direct-upload-${id}`)
element.classList.remove("direct-upload--pending")
})
addEventListener("direct-upload:progress", event => {
const { id, progress } = event.detail
const progressElement = document.getElementById(`direct-upload-progress-${id}`)
progressElement.style.width = `${progress}%`
})
addEventListener("direct-upload:error", event => {
event.preventDefault()
const { id, error } = event.detail
const element = document.getElementById(`direct-upload-${id}`)
element.classList.add("direct-upload--error")
element.setAttribute("title", error)
})
addEventListener("direct-upload:end", event => {
const { id } = event.detail
const element = document.getElementById(`direct-upload-${id}`)
element.classList.add("direct-upload--complete")
})
以上代码摘自:https://guides.rubyonrails.org/active_storage_overview.html#direct-uploads
答:
0赞
oskrgg
6/21/2020
#1
请尝试此 DirectUpload 指南部分。
直接使用类可以提交 .DirectUpload
remote: true
- 捕获提交 (
event.preventDefault()
) - 使用类上传文件。它提供了显示进度条和所有内容的事件。
DirectUpload
- 通过以下方式提交您的表格。
js
意味着更多的代码,但它是一种选择。
评论
$(file_field_id).closest('form').submit();