Ruby-on-rails 如何在rails中上传文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3933061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:22:51  来源:igfitidea点击:

How to upload a file in rails?

ruby-on-railsfilefile-uploadfilefield

提问by althaf_tvm

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

我是导轨的新手。我想了解 Rails 中的文件上传过程。任何人都可以帮我...谢谢,Althaf

回答by Jason stewart

Usually gems/plugins are used to to handle file uploads. My favorite one, and perhaps the most ubiquitous is Paperclip.

通常 gems/plugins 用于处理文件上传。我最喜欢的,也许是最普遍的一种是Paperclip

In your view, you'll have to tell the rails form helpers that you're uploading a file like this:

在您看来,您必须告诉 rails 表单助手您正在上传这样的文件:

<%= form_for @model, :html => { :multipart => true } do |form| %>

回答by Ballaji T

Here is a method on how to upload file without using any gem and only by using rails,

这是一种不使用任何 gem 仅使用 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.html.erb 应该包含这个,这很简单,

 <%= 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.