簡體   English   中英

在rails控制器中獲取Carrierwave上傳的文件名

[英]Get file name of Carrierwave upload in rails controller

我需要在我的控制器中獲取文件名和上傳文件,以便我可以為上傳的文件設置默認標題(或名稱),如果用戶沒有分配一個。 我使用Carrierwave上傳文件。

我的控制器創建動作如下所示:

  def create
    @photo = Photo.new(params[:photo])
    @photo.user_id = current_user.id


    respond_to do |format|
      if @photo.save
        format.html { redirect_to @photo, notice: 'Photo was successfully created.' }
        format.json { render action: 'show', status: :created, location: @photo }
      else
        format.html { render action: 'new' }
        format.json { render json: @photo.errors, status: :unprocessable_entity }
      end
    end
  end

解決方案是從carrierwave文件中獲取文件名,如下所示:

  def create
    @photo = Photo.new(params[:photo])
    @photo.user_id = current_user.id

    @photo.name =  @photo.image.file.filename if @photo.name == ""

    respond_to do |format|
      if @photo.save
        format.html { redirect_to @photo, notice: 'Photo was successfully created.' }
        format.json { render action: 'show', status: :created, location: @photo }
      else
        format.html { render action: 'new' }
        format.json { render json: @photo.errors, status: :unprocessable_entity }
      end
    end
  end

暫無
暫無

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

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