我的用户上传了一个包含 3 个文件(A.ttf、A.svg、A.otf)的 zip 文件,我想在其中存储原始 zip 文件和 3 个字体文件。我用这段代码创建了 3 个版本
version :ttf
process :font => :ttf
end
version :svg
process :font => :svg
end
version :otf
process :font => :otf
end
它成功保存了原始文件的 4 个副本,所有副本都具有正确的文件名。但是,我不知道如何让 CarrierWave 存储单个文件。此代码不起作用。 :(
def font(format)
new_file = nil
# Loop through the zip file and extract the files
Zip::ZipFile.open(@file.file) do |files|
files.each do |f|
next unless f.file?
filename = f.name.split("/").last
ext = filename.split('.').last
# Save the file with the proper file extension
new_file = f if ext == format
end
# Return the file to be stored by CarrierWave
new_file
end
最佳答案
好吧,我的头撞在墙上好几个小时后,灯终于亮了。解决方案在于 CarrierWave 如何处理上传。当您定义一个版本时,CW 会使用新名称 ([version name]_original_filename) 复制该文件,并在 current_path
变量中将其提供给您。您可以使用此文件引用做任何您想做的事情(即打开文件并截断它,或用随机日期填充它等),完成后 CW 将为您存储该文件。
不知何故,我错过了联系,当我意识到发生了什么事时,我几乎失明了。我在这里回答这个问题是为了帮助其他一些迷失在黑暗中的可怜人。并向世界展示我的无知。 :/
关于ruby-on-rails - 如何在 CarrierWave 进程中创建新文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4968027/