0

我在 Rails 5 中使用 Shrine gem。我启用了插件 upload_endpoint、versions、processing 和 recache。我希望在上传端点响应中获得生成的版本。

class VideoUploader < Shrine
  plugin :processing
  plugin :versions
  plugin :recache
  plugin :upload_endpoint

  plugin :upload_endpoint, rack_response: -> (uploaded_file, request) do

    # ??? I expected uploaded_file to have thumbnail version here ???

    body = { data: uploaded_file.data, url: uploaded_file.url }.to_json
    [201, { "Content-Type" => "application/json" }, [body]]
  end

  process(:recache) do |io, context|
    versions = { original: io }

    io.download do |original|
      screenshot = Tempfile.new(["screenshot", ".jpg"], binmode: true)
      movie = FFMPEG::Movie.new(original.path)
      movie.screenshot(screenshot.path)
      screenshot.open # refresh file descriptors

      versions[:thumbnail] = screenshot
    end

    versions
  end
end

为什么只有在保存整个记录时才会发生进程回调进程(:recache)?以及如何使其在直接上传后立即生成版本?

4

1 回答 1

2

:recache操作仅在您将文件分配给模型实例并且验证成功后才会发生。所以这个recache插件不是你想要的。

每当 Shrine 上传文件时,它都会:action在该上传文件中包含一个参数,这就是您注册process块时匹配的内容。它目前没有记录,但upload_endpoint包含action: :upload,所以只需使用process(:upload)

process(:upload) do |io, context|
  # ...
end

在您的:rack_response块中,uploaded_file现在将是上传文件的哈希,因此您将无法调用#data它。但是您可以直接将它们包含在哈希中,它们应该会自动转换为 JSON。

  plugin :upload_endpoint, rack_response: -> (uploaded_file, request) do
    body = { data: uploaded_file, url: uploaded_file[:original].url }.to_json
    [201, { "Content-Type" => "application/json" }, [body]]
  end
于 2019-04-10T11:56:56.533 回答