【问题标题】:Carrierwave Uploader specify Version directory using same file name for Rails 5Carrierwave Uploader 为 Rails 5 使用相同的文件名指定版本目录
【发布时间】:2018-11-02 15:38:48
【问题描述】:

我想为我上传的文件版本使用相同的文件名但不同的目录。

upload file imageName.jpg should create
   uploads/drawing/2018/imageName.jpg    #which is the original file
   uploads/thumbs/2018/imageName.jpg     #a 120 x 100 scaled version of the original file

在我的: 类 DrawingUploader

我重写了 store_dir 方法,该方法将我下载的文件 imageName.jpg 正确存储在 uploads/drawings/2018 中

def store_dir
    "uploads/drawings/2018"
end

然后我创建一个缩略图版本,我想指定文件名,使其与原始文件名相同(没有添加“thumb”)和一个目录。文件名适用于 full_filename 但 store_dir 不适用。

version :thumb do
  process resize_to_fit: [120, 100]

  def store_dir (for_file = model.drawing.file)
    "uploads/thumbs/2018"
  end
  def full_filename (for_file = model.drawing.file)
    "imageName.jpg"
  end
end

这会在 uploads/drawings/2018/imageName.jpg 存储一个 120x100 的文件

它仍在使用版本之前定义的 store_dir(图纸不是拇指)。

来自我的测试的更多信息:

如果调用uploader时文件uploads/drawings/2018/imageName.jpg已经存在,则version中定义的store_dir正常工作,并将文件放在uploads/thumbs/2018/imageName.jpg中

如果版本仅使用 full_filename,但我包含指定文件名的路径,它将将该路径放置在上传者上次使用的路径中,因此:

version :thumb do
   process resize_to_fit: [120, 100]

   def full_filename (for_file = model.drawing.file)
     "uploads/thumbs/2018/imageName.jpg"
   end
end

在 uploads/drawings/2018/uploads/thumbs/2018/imageName.jpg 创建一个文件

如果我尝试将路径设为相对路径,它会正确创建目录但从不写入版本文件——文件夹只是空的

version :thumb do
 process resize_to_fit: [120, 100]

 def store_dir (for_file = model.drawing.file)
   "../../uploads/thumbs/2018"
 end
 def full_filename (for_file = model.drawing.file)
   "imageName.jpg"
 end
end

在uploads/drawings/2018创建一个空目录文件imageName.jpg没有写入

【问题讨论】:

    标签: ruby-on-rails path version filenames carrierwave


    【解决方案1】:

    这似乎是缓存的载波问题。我发现这个 hack 非常有用:https://github.com/carrierwaveuploader/carrierwave/issues/1861

    我使用的如下:

    def store_dir
      if version_name
        @dirName = "thumbs"
      else
        @dirName = "drawings"
      end
    
      "uploads/#{@dirName}/2018"
    end
    
    def filename
      "newImage.jpg" if original_filename.present?
    end
    
    def full_filename(for_file)
      if model.new_record?
        super(for_file)
      else
        for_file
      end
    end
    
    # Create different versions of your uploaded files:
    version :thumb do
      process resize_to_fit: [120, 100]
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-18
      • 1970-01-01
      • 2017-07-06
      • 1970-01-01
      • 1970-01-01
      • 2015-07-16
      • 1970-01-01
      相关资源
      最近更新 更多