How to upload a file in rails?

前端 未结 2 1022
你的背包
你的背包 2021-01-03 10:41

I\'m new to rails. I want to know about file uploading process in rails. Can anyone please help me... Thanks, Althaf

2条回答
  •  灰色年华
    2021-01-03 10:44

    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 %>
          
    <%= f.submit "Upload" %>
    <% 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  for viewing video files.
    Use  for viewing audio files.
    Use "link" for viewing PDF or DOC files.
    

提交回复
热议问题