1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Railsで画像を保存するメモ

Posted at

ソースコード

  def create
    # 登録用
    product = Product.new(name:  params['name'], price: params['price'], description: params['description'])

    if params[:image]
      extension = File.extname(params[:image].original_filename)
      random_filename = SecureRandom.uuid + extension
      product.image = random_filename
      image = params[:image]
      File.binwrite("public/products/#{product.image}", image.read)
    else
      product.image = "defalut.png"
    end

    if product.save
      flash[:notice] = "出品に成功しました"
      redirect_to('/home/top')
    else
      flash[:notice] = "出品に失敗しました"
      render("products/sell")
    end
  end

説明

extension = File.extname(params[:image].original_filename)
random_filename = SecureRandom.uuid + extension
  • extension = File.extname(params[:image].original_filename)
    • params[:image].original_filenameで元画像の拡張子を保存
    • File.extnameでファイル名から拡張子を取得
  • random_filename = SecureRandom.uuid + extension
    • ランダムな一意のファイル名を生成する
    • SecureRandom.uuidで一意のランダムな文字列を生成
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?