是否可以将 ActiveStorage 配置为在附加文件后立即开始上传,而不是在单击提交按钮时开始上传?

Can ActiveStorage be configured to start uploading as soon as the file is attached, as opposed to when the submit button is clicked?

我喜欢 Rails 5.2 中用于文件上传的新 ActiveStorage 模块的外观,但在我去为我的站点重写大量代码之前,似乎只有在用户单击提交按钮。

有谁知道是否可以将 ActiveStorage 配置为在附加文件后立即上传?

我不认为它内置于 Active storage 中。我还没有读过 Active storage 中的任何此类功能。

基本上,Active storage 的开发背后的想法是提供内置的载体替代 wave/paperclip 并直接上传到云端 s3/google 云端。

使用一些JS是可以的。因为您可以通过创建图像部分作为单独的表单手动提交并使用 javascript.

提交

是的,可以使用 activestorage 的“DirectUpload”class。它是一个javascript class activestorage 内部用来创建文件对象并直接上传到指定服务。

使用处理文件更改事件和创建 "DirectUpload" class.

的对象,您可以在附加文件后立即创建直接上传文件

这是一个简短的例子

import { DirectUpload } from "activestorage"

  // on file selection or change {
  const url = element.dataset.directUploadUrl
  const upload = new DirectUpload(file, url)

  upload.create((error, blob) => {
    if (error) {
      // Handle the error
    } else {
      // Add an appropriately-named hidden input to the form with a value of blob.signed_id
      $('<input>').attr({
        type: 'hidden',
        name: 'your_object[files][]',
        value: blob.signed_id
      }).appendTo('form');
    }
  })
// }

执行上传到 activestorage 后,您可以使用

提交表单
$("form").submit()

这会将上传的内容附加到您的 rails 模型对象。请记住,您必须在其中更新带有签名 ID 的表单,否则它不会将上传附加到您的模型对象。

我最近在我的一个项目中使用了上述流程。