使用Cloudinary和Active Storage时如何设置文件上传到特定文件夹?

Gin*_*ino 2 jobs ruby-on-rails http-headers cloudinary rails-activestorage

我明白当使用以下语法直接上传到 Cloudinary 并将文件夹名称作为参数传递时,这是如何下降的。

Cloudinary::Uploader.upload("sample.jpg", :use_filename => true, :folder => "folder1/folder2")
Run Code Online (Sandbox Code Playgroud)

但是,我正在使用 ActiveStorage,当我以上述方式上传照片时,它不会附加到我的Post模型或以任何方式与我的应用程序关联。

我正在使用以下代码附加图像

post.send(:images).attach io: StringIO.new(new_data), filename: blob.filename.to_s, 
          content_type: 'image'
Run Code Online (Sandbox Code Playgroud)

它不接受指定文件夹的参数。我已尽力阅读 ActiveStorage 和 Cloudinary 文档,试图找到一种方法来完成这项工作,但是,我似乎无法弄清楚。

我已经看到设置自定义文件夹标头可能是使其工作的一种方法,但再次无法弄清楚如何为下面发生的上述代码设置自定义标头job

require 'tmpdir'
require 'fileutils'
require 'open-uri'
class ResizeImagesJob < ApplicationJob
  queue_as :default

  def perform(post)
    post.images.each do |image|
      blob = image.blob
      blob.open do |temp_file|
        path = temp_file.path
        pipeline = ImageProcessing::MiniMagick.source(path)
        .resize_to_limit(1200, 1200)
        .call(destination: path)
        new_data = File.binread(path)
        post.send(:images).attach io: StringIO.new(new_data), filename: blob.filename.to_s, 
                           content_type: 'image'
      end
      image.purge_later
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

上述工作正在做的是等到帖子创建后,然后调整照片大小并将照片重新附加到帖子以及删除原始照片。我采用这种方法是为了避免上传后直接在 Cloudinary 上调整帖子大小时发生的完整性错误。

我想要做的是将调整大小的照片存储在不同的文件夹中。这样做的原因是我正在使用direct_upload,并且用户可以在不创建帖子的情况下上传照片。因此导致我存储未使用的照片。这将提供一种识别和处理此类图像的简单方法。

Fla*_*che 5

对于基于 Rails 环境的文件夹名称

\n

您可以在 storage.yml 上动态设置文件夹:

\n
cloudinary:\n  service: Cloudinary\n  folder: <%= Rails.env %>\n
Run Code Online (Sandbox Code Playgroud)\n

因此 Cloudinary 将根据您的 Rails 环境自动创建文件夹:

\n

图像

\n

这是 Active Storage 的一个长期存在的问题,Cloudinary 团队似乎已经解决了这个问题。感谢您的出色工作 \xe2\x9d\xa4\xef\xb8\x8f

\n