我想在我的控制器中创建一个功能来保存管理员上传的图片。我不想使用插件或Activerecord,只是将图片的字节写入app / assets / images /目录的函数。
因此,当管理员创建新产品时,他会将产品图片放入应用程序中。
我想在create
的操作Product Controller
中使用此功能。
这样,在将新产品保存在db之前,图片将保存到app中(不在db中,我只想写字节)。
我在互联网上搜索,我创建了一个保存图片的功能。
我有一个奇怪的错误:undefined method
阅读' 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
谢谢你的帮助。
编辑:新错误
答案 0 :(得分:1)
由于您使用的是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) }