How to upload a file in ruby on rails?

后端 未结 4 2144
有刺的猬
有刺的猬 2021-02-01 06:16

I’m very new in ruby on rails. I’m stuck with a problem. I want to make a file upload functionality through which I can upload any kind of file (text,image etc.). My controller

4条回答
  •  眼角桃花
    2021-02-01 06:27

    Thank you for example, I study rails too!

    It works in rails 3.1

    My code:

    Routes
    resources :images do
          collection { post :upload_image }
        end
    

    Controller

    class ImagesController < ApplicationController
      def index
        @car = Car.find(params[:car_id])
        @images = @car.images.order("order_id")
      end
    
      def upload_image   
        DataFile.save_file(params[:upload])
        redirect_to images_path(:car_id => params[:car_id])
      end
    

    View index.html.erb

    File Upload

    <%= form_tag({:action => 'upload_image', :car_id => @car.id}, :multipart => true) do %>

    <%= file_field 'upload', 'datafile' %>

    <%= submit_tag "Upload" %> <% end %> <% @images.each do |image| %> <%= image.id %>
    <%= image.name %> <% end %>

    Model

    class DataFile < ActiveRecord::Base
        attr_accessor :upload
    
      def self.save_file(upload)   
    
        file_name = upload['datafile'].original_filename  if  (upload['datafile'] !='')    
        file = upload['datafile'].read    
    
        file_type = file_name.split('.').last
        new_name_file = Time.now.to_i
        name_folder = new_name_file
        new_file_name_with_type = "#{new_name_file}." + file_type
    
        image_root = "#{RAILS_CAR_IMAGES}"
    
    
        Dir.mkdir(image_root + "#{name_folder}");
          File.open(image_root + "#{name_folder}/" + new_file_name_with_type, "wb")  do |f|  
            f.write(file) 
          end
    
      end
    end
    

提交回复
热议问题