簡體   English   中英

在 ruby​​ on rails 上重命名上傳文件

[英]Rename an upload file on ruby on rails

我是 ruby​​ on rails 的新手,我想更改我上傳的圖片的名稱 謝謝

def resize_image
  resized_image = MiniMagick::Image.read(picture.image.download)
  resized_image = resized_image.combine_options do |b|
    b.resize '2760>'
    b.quality '80'
  end
  v_filename = picture.image.filename
  v_content_type = picture.image.content_type
  picture.image.purge
  picture.image.attach(io: File.open(resized_image.path), filename: v_filename, content_type: v_content_type)
end

picture.image.filename屬於ActiveStorage::Filename類,因此gsub無法解決我們需要先使用to_s方法將其轉換為字符串的問題,然后我們可以使用gsub將空格( )替換為下划線(_)

v_filename = v_filename.to_s.gsub(" ", "_")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM