使用 Rails 中的 f.file_field 确保只能上传文本文件

Making sure that only text files can be uploaded using f.file_field in Rails

我在 Rails 中的 html.slim 中有 = f.file_field "file", required: true, class: "filestyle"。如何确保只能上传扩展名为 .txt 的文本文件,而不能上传扩展名为 .png.jpg

的其他文件

尝试使用 Paperclip or carrierwave gem.This 应该会让您的生活更轻松:)

使用:accept parameter of file_field:

:accept - If set to one or multiple mime-types, the user will be suggested a filter when choosing a file. You still need to set up model validations.

文本文件的 Mime 类型是 text/plain。所以你的字段看起来像这样:

= f.file_field "file", required: true, class: "filestyle", accept: "text/plain"