1

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

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 < CarrierWave::Uploader::Base

我重写了 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

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

它仍在使用版本之前定义的 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没有写入

4

1 回答 1

0

这似乎是缓存的载波问题。我发现这个 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
于 2018-05-23T16:31:27.380 回答