没有activerecord的文件上传 [英] file upload without activerecord

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

问题描述

如何在不将文件附加到活动记录的情况下处理 rail 中的文件上传?
我只想将文件写入磁盘.

How do you handle file upload in rail without attaching them to active record ?
I just want to write the files to the disk.

谢谢,

推荐答案

如果我正确理解你需要什么,那么最简单的例子是:

If I understand correctly what you need then the most simple example would be this:

控制器:

  class UploadController < ApplicationController
  def new

  end

  def create
    name = params[:upload][:file].original_filename
    path = File.join("public", "images", "upload", name)
    File.open(path, "wb") { |f| f.write(params[:upload][:file].read) }
    flash[:notice] = "File uploaded"
    redirect_to "/upload/new"
  end
end

视图:

<% flash.each do |key, msg| %>
    <%= content_tag :div, msg, :class => [key, " message"], :id => "notice_#{key}" %>
<% end %>
<% form_tag '/upload/create', { :multipart => true } do %>
    <p>
    <%= file_field_tag 'upload[file]' %>
    </p>
    <p>
        <%= submit_tag "Upload" %>
    </p>
<% end %>

这将使您无需任何检查或验证即可上传任何文件,我认为这没有那么有用.

This would let you upload any file without any checks or validations which in my opinion isn't that usefull.

如果我自己做,那么我会使用类似 validatable gemtableless gem 不再支持 tableless.这些 gem 可让您验证上传的内容,使其更加合理.

If I would do it myself then I would use something like validatable gem or tableless gem just tableless is not supported anymore. These gems would allow you to validate what you're uploading to make it more sane.

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

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