How to get the filename of uploaded file in rails contoller

柔情痞子 提交于 2021-02-20 19:26:30

问题


<%= file_field 'upload' %>

In my controller, if I give the following, based on suggestions

filename=params[:upload]
@result=filename.original_filename

I am getting.

undefined method `original_filename' for 
#<ActionController::Parameters:0x002b6c396e44b8> 

Note: I am not using form. Rails version is 4.0.2


回答1:


Use the following code in order to get the filename:

params[:file].original_filename



回答2:


Have you read how to upload files in Rails? Have you set your form to multipart: true? What will be in the params is either a StringIO or a File (depending on the size of the upload). On that object, you will have an original_filename attribute, which is the filename of the uploaded file.

edit: I see you said you aren't using a form to submit... What alternative steps have you taken to make that work in general?




回答3:


Did you add permit for :upload params

def some_params
   params.require(:something).permit(:upload)
end

[Refer on rails document] http://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-permit




回答4:


Try:

params[:pictures][0]["picture_path"].original_filename.split(".").first


来源:https://stackoverflow.com/questions/21979570/how-to-get-the-filename-of-uploaded-file-in-rails-contoller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!