Renaming uploaded files with Carrierwave

后端 未结 6 803
我寻月下人不归
我寻月下人不归 2021-01-31 08:46

I\'m using Carrierwave to upload files, and I have it working.

My issue is attempting to change the name of the uploaded file.

In the generated uploader.rb there

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-31 09:28

    Here is the solution, how to change the name of the file, if store_dir already contains the file with the exact name:

      if File.exists?(Rails.root.join("documents/" + "#{file.filename}")) && !path.to_s.eql?(Rails.root.join("documents/" + original_filename).to_s)
        @name ||= File.basename(original_filename, '.*') + Digest::MD5.hexdigest(File.dirname(current_path)).from(25)
        "#{@name}.#{file.extension}"
      else
        "#{original_filename}"
      end
    

    Note: Rails.root.join("documents/") is defined as my store_dir.

    Hope it helps someone.

提交回复
热议问题