2

This is my method for uploading files:

name = file.original_filename
directory = "images/"
path = File.join(directory, name)
File.open(path, "wb") { |f| f.write(file.read) }

I need to rename the uploaded file - I want to give it a unique name. But how can I obtain the file name and the extension?

One way on how to rename the file is from the filename remove the extension (.jpg - remove last 4 chars), rename the file and then merge the name+extension.

But this is a bit dirty way. Is there something cleaner and more elegant?

user1946705
  • 2,858
  • 14
  • 41
  • 58

2 Answers2

1

A 'little' late but I put this answer for those who are still searching and get here.

photo = params[:photo]
name = photo.original_filename
directory = "public/uploads/photos"
path = File.join(directory, name) 
uniq_name = (0...10).map { (65 + rand(26)).chr }.join
time_footprint = Time.now.to_formatted_s(:number)
File.open(path, "wb") do |file|
  file.write(photo.read)
  @uniq_path = File.join(directory, uniq_name + time_footprint + File.extname(file))
  File.rename(file, @uniq_path)
end

I take the random string generation from How to generate a random string in Ruby. And set @uniq_path to use it on a create function after.

0

What about doing this?

File.rename(file, folder_path + "/" + new_name + File.extname(file))

For example, calling this script on the same folder of the file:

new_name = "TESTING"

File.open("test.txt") do |file|
  File.rename(file, new_name + File.extname(file))
end

Will rename the file to: TESTING.txt

Kaeros
  • 1,138
  • 7
  • 7