How to upload a file in rails?

前端 未结 2 1002
你的背包
你的背包 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 %>
          <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.
    
    0 讨论(0)
  • 2021-01-03 10:57

    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| %>
    
    0 讨论(0)
提交回复
热议问题