在Rails中上传文件 [英] Uploading a file in Rails

查看:144
本文介绍了在Rails中上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是rails新手,正在使用CRUD技术编写一个RESTful网站。到目前为止,我已经创建了三个页面,所有这些页面都允许用户创建,编辑和删除数据库中的一行。不过,我的第四页需要包含一个上传文件的形式,但是a)我不知道文件系统如何与Rails协同工作,因此我不知道应该在哪里存储文件。该文件将是100kb左右,不能存储在临时存储,因为它会不断下载。和b)我不知道如何写入一个文件。

I'm new to rails, and I'm writing a RESTful website using the CRUD technique. So far I have created three pages, all of which allow the user to create, edit, and delete a row from the database. However, my fourth page will need to include an upload file form, but a) I don't know how the filesystem works with Rails thus I don't know where files should be stored. The file would be around 100kb and couldn't be stored in temporary storage because it will be constantly downloaded. And b) I don't know how to write to a file.

如果你能告诉我如何去做我上面提到的 - 创建一个上传输入一个输入表单,然后将文件写入一个文件路径到一个单独的目录中。

It would be great if you could tell me how to do what I mentioned above - create an upload input on an input form, and to then write the file to a filepath in a separate directory.

推荐答案

虽然有很多解决文件上传非常好的宝石(请参阅 https://www.ruby-toolbox.com/categories/rails_file_uploads 对于列表),rails有内置的帮助器,可以很容易地推出自己的解决方案。

While there are plenty of gems that solve file uploading pretty nicely (see https://www.ruby-toolbox.com/categories/rails_file_uploads for a list), rails has built-in helpers which make it easy to roll your own solution.

使用 file_field -form助手在你的表单中,而rails则为你处理上传:

Use the file_field-form helper in your form, and rails handles the uploading for you:

<%= form_for @person do |f| %>
  <%= f.file_field :picture %>
<% end %>

您可以在控制器中访问上传的文件,如下所示:

You will have access in the controller to the uploaded file as follows:

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

这取决于你想要达到的复杂性,但是这对于简单的文件上传/下载任务是完全足够的。这个例子是从导轨指南,你可以去那里获得更多的信息: http://guides.rubyonrails.org /form_helpers.html#uploading-files

It depends on the complexity of what you want to achieve, but this is totally sufficient for easy file uploading/downloading tasks. This example is taken from the rails guides, you can go there for further information: http://guides.rubyonrails.org/form_helpers.html#uploading-files

这篇关于在Rails中上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆