【问题标题】:Rails: Image upload (WIthout plugin's)Rails:图片上传(没有插件)
【发布时间】:2012-11-05 12:25:42
【问题描述】:

我有一张存储有关酱汁信息的表格。每个酱汁在图像资产文件夹中都有一个图像,在一个名为酱汁的文件夹中。所有酱汁文件的名称都相同; 例如assets/images/sauces/sauces_piri.png

我想要做的基本上就是以创建发生的形式上传一个 .png 文件,在 pic_url 的字段中,图像的名称与调味汁/一起存储,因此在我需要时可以正确定向显示图像。

目前管理员必须使用域文件管理将图片物理上传到正确的位置,并在创建新酱时输入“酱汁/酱汁名称.png”。

添加新酱的表格:

<%= error_messages_for(@sauce) %>
   <table summary="Sauces Form Fields">
    <tr>
     <th><%= f.label(:name,"Sauce Name") %></th>
     <td><%= f.text_field(:name) %></td>
    </tr>
    <tr>
     <th><%= f.label(:description, "Description") %></th>
     <td><%= f.text_area(:description, :size => '40x5') %></td>
    </tr>
    <tr>
     <th><%= f.label(:heat_level, "Heat Level") %></th>
     <td><%= f.select(:heat_level,{ 1 => "1", 2 => "2", 3 => "3", 4 => "4", 5 => "5"}) %></td>
   </tr>
   <tr>
    <th><%= f.label(:pic_url, "Picture URL") %></th>
    <td><%= f.text_field(:pic_url) %></td>
   </tr>
   <tr>
    <th><%= f.label(:title_colour, "Title Colour") %></th>
    <td><%= f.text_field(:title_colour) %></td>
   </tr>
   <tr>
    <th><%= f.label(:description_colour, "Desc Colour") %></th>
    <td><%= f.text_field(:description_colour) %></td>
   </tr>
  </table>

因此,如果不使用回形针等插件,我如何启用图像上传,然后将文件存储在正确的位置,以及在表字段pic_url 中存储文件夹名称/文件名.png?

【问题讨论】:

  • 那么,问题出在哪里?或者它是一个写它的请求?尝试并发布您遇到的问题。
  • 问题就在那里。我会改写一下,让它更明显。
  • 看看this question,它可能会提供一些帮助

标签: ruby-on-rails image forms upload


【解决方案1】:

我不清楚您遇到了什么问题。所以,我将发布一个关于上传文件的示例表单。

<%= form_for(:uploaded_data_file, :url => upload_files_path(:params => params) ,  :remote => true, :html => { :multipart => true } ) do |f| %>
  <%= f.label "Upload" %><br />
  <%= f.file_field :location %>
<% end %>

您必须为将存储图像的函数定义路径,在此示例中它称为upload_files_path,我们将所有params 传递给它。然后重启 webapp 获取新路由。

在控制器中,您可以保存文件及其详细信息

获取文件名

params[:uploaded_data_file][:location].original_filename

获取文件本身并保存

File.open("where/to/save", "wb") { |f| f.write(params[:uploaded_data_file][:location].read) }

为了确保它是 .png,您可以进行一些正则表达式检查

if(name =~ /.png$/i) # for more than one type do (name =~ /.jpeg$|.png$/i)

要执行其他操作,请查看您的 params 并进行所需的更改。

上班路线可以看http://edgeguides.rubyonrails.org/routing.html#adding-more-restful-actions

resources :posts do
  collection do
    get :upload_files # will create upload_files_posts_path
  end
end

或者

match '/upload_files', :to => 'controller_name#method_name' # 'posts#upload_files'

或者

<% form_tag({:action => 'upload_file'}  #will use the correct controller based on the form

【讨论】:

  • 你在正确的路线上,有没有办法可以指定代码的去向,例如模型、控制器等,是否可以使其特定于我的酱汁模​​型?
猜你喜欢
  • 2023-03-17
  • 2013-07-09
  • 1970-01-01
  • 2014-04-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-01
  • 1970-01-01
  • 2012-12-08
相关资源
最近更新 更多