开发者

Rails 3 - Tempfile Path?

I have the following:

attachments.each do |a|
   Rails.logger.info a.filename
   tempfile = Tempfile.new("#{a.filename}", "#{Rails.root.to_s}/tmp/")
   Rails.logger.info tempfile.path
end

Where attachments is from paperclip.

Here's the outp开发者_开发问答ut:

billgates.jpg
/Users/bhellman/Sites/cline/tmp/billgates.jpg20101204-17402-of0u9o-0

Why is the file name getting 20101204-17402-of0u9o-0 appended to at the end? That's breaking everything with paperclip etc. Anyone seen this before? For the life of I have no idea what's doing it?

Thanks

UPDATE Paperclip: Paperclip on github

a is the attachment file

tempfile = Tempfile.new("#{a.filename}", "#{Rails.root.to_s}/tmp/")
tempfile << a.body
tempfile.puts
attachments.build(
    :attachment => File.open(tempfile.path)
)


best make sure your tempfile has the correct extension, saving you to trying and change it after:

file = Tempfile.new(['hello', '.jpg'])

file.path # => something like: "/tmp/hello2843-8392-92849382--0.jpg"

more here: http://apidock.com/ruby/v1_9_3_125/Tempfile/new/class


The first argument for Tempfile.new is just a basename. To make sure each Tempfile is unique the characters are appended to the end of the file.


You should use Paperclip's API for this:

tempfiles = []
attachments.each do |a|
  # use Attachment#to_file to get a :filesystem => file, :s3 => tempfile
  tempfiles << a.to_file
end

tempfiles.each do |tf|
  Rails.logger.debug tf.filename
end


attachment = attachments.build(
  :attachment => File.open(tempfile.path)
)

# change the displayed file name stored in the db record here
attachment.attachment_file_name = a.filename # or whatever else you like

attachment.save!


The best way I found to deal with this was to specify the file extension in the Paperclip attribute. For example:

has_attached_file :picture,
  :url => "/system/:hash.jpg",
  :hash_secret => "long_secret_string",
  :storage => :s3,
  :s3_credentials => "#{Rails.root}/config/s3.yml"

Note that the :url is declared as '.jpg' rather than the traditional .:extension.

Good luck!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜