上传图片 无插件 无活动记录

Upload picture NO plugin NO activerecord

我想在我的控制器中创建一个功能来保存管理员上传的图片。我不想使用插件或 Activerecord,只是一个将图片的字节写入目录 app/assets/images/ 的函数。 因此,当管理员创建新产品时,他会将产品图片放入应用程序中。 我想在 Product Controller 的动作 create 中使用这个函数。 这样,在将新产品保存到数据库之前,图片将保存到应用程序中(不在数据库中,我只想写字节)。 我在互联网上搜索并创建了一个保存图片的功能。 我有一个奇怪的错误:undefined methodread' for "picture.png":String` 这是我所有的东西:

edit.html.erb

<h1>Editing product</h1>

<%= render 'form' ,:multipart => true%>

<%= link_to 'Show', @product %> |
<%= link_to 'Back', products_path %>

_form.html.erb

<%= form_for(@product) do |f| %>
  <% if @product.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@product.errors.count, "error") %> prohibited this product from being saved:</h2>

      <ul>
      <% @product.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :description %><br>
    <%= f.text_area :description %>
  </div>
  <div class="field">
    <%= f.label :image_url %><br>
    <%= f.text_field :image_url %>
  </div>
  <div class="field">
    <%= f.label :price %><br>
    <%= f.text_field :price %>
  </div>
  <div class="field">
    <%= f.label :upload %><br>
        <%= file_field :upload, :datafile %></p>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

product_controller.rb

  def create

        name =  params[:upload][:datafile]
    directory = Rails.root.join('app', 'assets','images')
    # create the file path
    path = File.join(directory, name)
    # write the file
    File.open(path, "wb") { |f| f.write(params[:upload][:datafile].read) }


    @product = Product.new(product_params)

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

谢谢你的帮助。

编辑:新错误

由于您使用的是 form_for,实际的临时文件将在 params[:product][:upload] 中。试试这个

_form.html.erb 部分中,将 file_field 行更改为

<%= file_field :upload %>

然后,在您的 create 操作中

name = params[:product][:upload].original_filename
directory = Rails.root.join('app', 'assets','images')
# create the file path
path = File.join(directory, name)
# write the file
File.open(path, "wb") { |f| f.write(params[:product][:upload].read) }