rails - Paperclip file name
Asked Answered
P

4

19

using rails with Paperclip, I can use the following to get the filename during a before_create:

extension = File.extname(photo_file_name).downcase

How do I get JUST the file name.. Right now I have photo_file_name which provides the entire file, titlename.pdf

i need just titlename without the .pdf

Thanks

Updating with code:

photo.rb:

  before_create :obfuscate_file_name

  #Paperclip for photo
  has_attached_file :photo,
......


private

  def obfuscate_file_name
    extension = File.extname(photo_file_name).downcase
    fileNameOnly = File.basename(photo_file_name).downcase
    self.photo.instance_write(:file_name, "#{fileNameOnly}_#{ActiveSupport::SecureRandom.hex(32)}#{extension}")
  end
Photophore answered 29/11, 2010 at 18:21 Comment(0)
M
26

Use File.basename with the optional suffix argument like this:

file_name = File.basename(photo_file_name, File.extname(photo_file_name));

Works on my machine:

alt text

Mayolamayon answered 29/11, 2010 at 18:23 Comment(1)
Stackoverflow makes you wait 6 mins.Photophore
M
23

Paperclip attachment has the 'original_filename' method for this.

Minoru answered 19/10, 2014 at 12:55 Comment(2)
I'm not sure this will give what the OP wants. They want a_file, not a_file.pdf?Erna
Seems like the title of this question is maybe not specific enough. People probably come here searching for "paperclip filename", and find this answer which is the correct answer to that question, so they upvote it even though it's not what the OP of this question asked.Petrie
C
11
user.logo.original_filename
  => 'test.jpg'
Cambria answered 19/1, 2016 at 7:35 Comment(0)
T
0

Another option is set to default, work for all upload.

This example change name file to 'name default' for web, example: test áé.jpg to test_ae_www.foo.com.jpg

helper/application_helper.rb

def sanitize_filename(filename)
    fn = filename.split /(?<=.)\.(?=[^.])(?!.*\.[^.])/m
    fn[0] = fn[0].parameterize
    return fn.join '.'
end

Create config/initializers/paperclip_defaults.rb

include ApplicationHelper

Paperclip::Attachment.default_options.update({
    :path => ":rails_root/public/system/:class/:attachment/:id/:style/:parameterize_file_name",
    :url => "/system/:class/:attachment/:id/:style/:parameterize_file_name",
})

Paperclip.interpolates :parameterize_file_name do |attachment, style|
    "#{sanitize_filename(attachment.original_filename)}_www.foo.com"
end

Need restart, after put this code

I hope it help! ;)

Teletype answered 8/3, 2017 at 2:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.