我需要在 Controller 中获取和上传文件的文件名,以便如果用户未分配文件,则可以为上传文件设置默认标题(或名称)。我使用Carrierwave上传ing文件。
我的 Controller 创建 Action 如下所示:
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
最佳答案
解决方案是从载波文件中获取文件名,如下所示:
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
关于ruby-on-rails - 在Rails Controller 中获取Carrierwave上传的文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20933619/