Ruby on rails achieve image upload

A few days ago to do a picture upload function, just do it, but the other controller bound together in a disorderly, for example a student for several pictures, the database link, a one to many relationship, should be set to a multiple picture, can give me a case it?

Started by Sabrina at November 10, 2016 - 4:43 AM

Method of realizing multi picture upload and preview picture is similar, all is by sending a message to the method, and then the method of rendering a div to add a file_field control to. And the different points in the preview to determine which file_filed sent the message, so as to render to preview in the relevant areas. Here we pass a variable @file_id to transfer, regional ID each rendering are expressed using @file_id. Such as:

<div id = "file_field_<%= @file_id %>">
<%= file_field_tag("attachment[#{@file_id}][]", :onchange => "this.form.action = '#{url_for :controller => 'myblog', :action => 'project_image_preview', :file_id => @file_id }';this.form.submit();", :size =>50) %>
<div id = 'image_preview_<%= @file_id %>'></div>
<div id = "delete_button_<%= @file_id %>"></div>

The most important thing is how to receive documents, with an array of attachment, received key = params[: file_id], file = params["attachment"][key].first that made file, then you can render the preview area.
In addition, in the preservation of multiple pictures should also pay attention to, first using the iteration determine whether each file uploading area, and then save.

def self.upload(file_array, id)
#In the file_array form is hash{1=> 'file1', 2 => 'file2'}
file_path = "#{RAILS_ROOT}/public/images/uploaddata/#{id}/"
pp file_path
if !File.exist?(file_path)
Dir.mkdir(file_path, 0777)
file_array.each do |key,value| # Iterative preservation
file = value[0]
original_name = file.original_filename
save_name = UUIDTools::UUID.random_create.to_s[0,4] + original_name
if file.present? # If the file exists
file_name = file_path + save_name
if File.exist?(file_name)
end,"wb") do |f|

Posted by Truman at November 13, 2016 - 5:29 AM