![]() |
rails - Paperclip file name - Printable Version +- 0Day Forums (https://0day.red) +-- Forum: Coding (https://0day.red/Forum-Coding) +--- Forum: Ruby (https://0day.red/Forum-Ruby) +--- Thread: rails - Paperclip file name (/Thread-rails-Paperclip-file-name) |
rails - Paperclip file name - machiavellianly659295 - 07-19-2023 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 RE: rails - Paperclip file name - convict194239 - 07-19-2023 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! ;) RE: rails - Paperclip file name - vermis71 - 07-19-2023 user.logo.original_filename => 'test.jpg' RE: rails - Paperclip file name - extraversion563382 - 07-19-2023 Paperclip attachment has the 'original_filename' method for this. RE: rails - Paperclip file name - bichromenrmz - 07-19-2023 Use [`File.basename`][1] 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][2] [1]: [To see links please register here] [2]: |