使用Carrierwave重命名上传的文件 [英] Renaming uploaded files with Carrierwave

查看:307
本文介绍了使用Carrierwave重命名上传的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我的问题是试图更改上传文件的名称。

我使用Carrierwave上传文件,

在生成的uploader.rb中有一个方法,我想我应该使用

pre $ code > def filename
something.jpgif original_filename
asename =what+ orginal_filename if original_filename,works
asename =(0 ... 8).map {65。+(rand (25)).chr} .join如果original_filename#将为每个版本创建一个随机名称,例如数据库中的原始,缩略图和文件名,无用
结束

我可以在sanitized_file.rb中似乎无法访问诸如扩展名或content_type这样的项目,所以现在有点超出了我目前的技能水平。

任何建议或这样做的练习,即生成一个上传文件的文件名,以及载波默认(不做任何事情,但会继续到每个版本)?好像,它应该很简单,但我偶然发现了这一点。

那么,您的随机文件名生成器的另一个问题是那有可能碰撞是不是?你可能会生成一个已经生成的文件名。
去一个方法是以某种方式生成基于图像的独特属性,如文件路径哈希。例如,从载波

  def filename 
如果original_filename
@name || = Digest :: MD5.hexdigest(File.dirname(current_path))
#{@name}.#{file.extension}
end
end

这将根据当前路径创建一个MD5散列,然后将原始文件的扩展名附加到它。



编辑: carrierwave wiki添加了一个 entry ,并提供了一些关于如何为所有版本化文件创建随机和唯一文件名的方法。


I'm using Carrierwave to upload files, and I have it working.

My issue is attempting to change the name of the uploaded file.

In the generated uploader.rb there is a method I think I should be using

def filename
   "something.jpg" if original_filename
   basename = "what"+orginal_filename if original_filename, works
   basename = (0...8).map{65.+(rand(25)).chr}.join if original_filename  # will create a random name for each version, e.g. the orginal, the thumb, and the filename in the db, useless
 end

I can't seem to access items like 'extension' or 'content_type' in sanitized_file.rb, so this is a bit beyond my current skill level right now.

Any suggestions or exercises for doing this, i.e. generate filename for an uploaded file that works as well as the carrierwave default (do nothing, but does carry on to each version)? Seems like it should be simple enough but I've stumbled over this.

解决方案

Well, another problem with your random filename generator is that it's possible to have collisions isn't it? You could possibly generate a filename that was already generated. One way to go about it would be to somehow generate a hash based on unique properties of the image, like file path. An example, from the carrierwave group:

def filename 
  if original_filename 
    @name ||= Digest::MD5.hexdigest(File.dirname(current_path))
    "#{@name}.#{file.extension}"
  end
end

This will create an MD5 hash based on the current path and then append the original file's extension to it.

Edit: The carrierwave wiki added an entry with a few methods on how to create random and unique filenames for all versioned files.

这篇关于使用Carrierwave重命名上传的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆