问题
I'm new to rails. I want to know about file uploading process in rails. Can anyone please help me... Thanks, Althaf
回答1:
Usually gems/plugins are used to to handle file uploads. My favorite one, and perhaps the most ubiquitous is Paperclip.
In your view, you'll have to tell the rails form helpers that you're uploading a file like this:
<%= form_for @model, :html => { :multipart => true } do |form| %>
回答2:
Here is a method on how to upload file without using any gem and only by using rails,
Solution :=>
def create
@photo = Photo.new(photo_params)
uploaded_io = params[:photo][:photo]
File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'wb') do |file|
file.write(uploaded_io.read)
end
if @photo.save
flash[:success] = "The photo was added!"
redirect_to root_path
else
render 'new'
end
end
def upload
uploaded_io = params[:person][:picture]
File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'wb') do |file|
file.write(uploaded_io.read)
end
end
And your form.html.erb in views should contain this, it is very simple,
<%= form_for @photo do |f| %>
<%= f.file_field :photo %>
<div class="actions">
<%= f.submit "Upload" %>
</div>
<% end %>
and finally the model should have ,
has_attached_file :image
.################################################## You can now enjoy loading any file .
Thank you. Have funn with rails.
Use <video_tag> for viewing video files.
Use <audio_tag> for viewing audio files.
Use <object>"link"</object> for viewing PDF or DOC files.
来源:https://stackoverflow.com/questions/3933061/how-to-upload-a-file-in-rails