trnc
trnc

Reputation: 21577

Overwrite when uploading files with rails?

i upload files in rails with following code:

name = upload['datafile'].original_filename
directory = "public/data/#{id}/#{app_id}"

Dir.mkdir("#{RAILS_ROOT}/public/data/#{id}/#{app_id}")

path = File.join(directory, name)

File.open(path, "wb") { |f| f.write(upload['datafile'].read) }

can someone tell me how i can tell rails, that it should overwrite the file when it already exists?

thanks!

Upvotes: 1

Views: 1395

Answers (1)

Vasiliy Ermolovich
Vasiliy Ermolovich

Reputation: 24617

You should check if a dir already exist:

name = upload['datafile'].original_filename
directory = "public/data/#{id}/#{app_id}"

Dir.mkdir("#{RAILS_ROOT}/public/data/#{id}/#{app_id}") unless Dir.exist? "#{RAILS_ROOT}/public/data/#{id}/#{app_id}"

path = File.join(directory, name)

File.open(path, "wb") { |f| f.write(upload['datafile'].read) }

Upvotes: 2

Related Questions