简体   繁体   English

在rails控制器中获取Carrierwave上传的文件名

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

I need to get the file name of and uploaded file in my controller so that i could set a default title (or name) to the uploaded file if the user did not assign one. 我需要在我的控制器中获取文件名和上传文件,以便我可以为上传的文件设置默认标题(或名称),如果用户没有分配一个。 I use Carrierwave to upload ing files. 我使用Carrierwave上传文件。

My controller create action looks like this: 我的控制器创建动作如下所示:

  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

The solution was to get the filename from the carrierwave file like this: 解决方案是从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