I’ve been having trouble trying to get uploaded images to save
correctly to a blob field in a MySQL database.
Here’s my form view
VIEW:
<% form_for(@user, :html => { :class => ‘edit’,:multipart => true })
do |f| %>
Picture <%= error_message_on(:user, :picture) %>
<%= f.submit "Submit" %>
<% end %>
…which produces the correct form header, so I know multipart is
working:
Here’s my code for saving the picture to the db:
CONTROLLER:
if !params[:user][:picture].blank?
params[:user][:picture].rewind # Recommended to add
@user.picture = params[:user][:picture].read
end
In an irb console, I can see that params[:user][:picture].class ==
ActionController::UploadedStringIO
irb(#UsersController:0x7ee75580):006:0> params[:user]
[:picture].class
=> ActionController::UploadedStringIO
I can also see the binary blob of the file when I try and read it:
irb(#UsersController:0x7ee75580):003:0> @user.picture = params[:user]
[:picture].read
=> “GIF89aÈÈ÷\e>\032\036>\034!?"&>\032\036C\032\035H\035"E\036#
L\037(G\036)K\037&Q!%D"&M$)F$(M)-M$‘P"’[$Q$Y-S-Y,1F-1M,2U-
2Y26M14U26[6;S59]9?V:=]6=a;>b>B]>Ad?IcBE[FI]IM_BEdCGlFJeFIkIM
cILlFJqJNrMPeMQlNQqRUmSXl]\oSUsUXuZ]{^a}cd|fi|hj|^a\200ce\202fi\2
…(it’s long)…
270ÇMîrûÜèN·\272×Íîv>>ûÝð·\274çMïzÛûÞøÎ·\276\005\025\020\000;”
Once it’s saved into the db:
irb(#UsersController:0x7ee75580):005:0> @user.picture.class
=> String
But when I try to view the same image in the Rails view, it don’t
work. My co-worker uploaded several pictures to the blob field using
VB.net, and I can see his pictures just fine, but not mine.
Here’s my display code:
VIEW:
<%= image_tag("/users/picture?user_id=#{user.id}", :size => '60x60', :alt => "Picture") unless (user.blank? && user.picture.blank?) %> ==========CONTROLLER:
def picture
user = User.find_by_id(params[:user_id])
send_data(user.picture)
end
Now, I can do something like:
File.open(“/c/rails/public/tmp-pic.jpg”, ‘wb’) do |f|
f.write params[:user][:picture].read
end
And I can open up tmp-pic.jpg and view it, which means the upload
works, and the reading works, but just not saving to the db…
I don’t think it’s a file-type problem (.gif, .jpg, .png) since I
tried all three types, and still nothing.
I assume it’s reading it and storing it as a string, instead of as a
blob, but not really sure about MySQL and how it handles that, if
that’s even the problem.
Any help would be greatly appreciated!