ruby项目文件上传功能实现

这里我将从视图、控制器各个层面进行讲解。

 rails 提供了文件上传功能,可以直接进行下面的编码

<%= form_for :document, :html =>{:multipart => true} do |f| %>
  <%= f.file_field :file %>
  <%= f.submit "Upload" %>
<% end %>

控制器层面:

document_controller.rb中

 
#创建一个新文档
def create  
    @document = Document.new(document_params)
    unless request.get?
      filename = uploadfile(@document.file)
      @document.file = filename
     if  @document.save
       redirect_to list_documents_path
     else
       @document.file = nil
       render "new"
     end
    end
  end


def uploadfile(file)
    require 'net/ftp'
    if !file.original_filename.empty?  #file.original_filename 获取文件名字
      filename = CGI::escape(file.original_filename)
      FileUtils.mkdir("#{Rails.root}/public/upload") unless File.exist?("#{Rails.root}/public/upload")
      #wb 表示通过二进制方式写,可以保证文件不损坏
      File.open("#{Rails.root}/public/upload/#{filename}", "wb") do |f|
        f.write(file.read)
      end
      path = "#{Rails.root}/public/upload/#{filename}"
      local_file = path
      upload_cmd(SysUtils::FILE_SERVER[:host], SysUtils::FILE_SERVER[:user], SysUtils::FILE_SERVER[:passwd]) do |conn|  #打开文件服务器
        conn.chdir("/platform_tools/document")  #切换到保存文档的目录
        cur_files = conn.nlst
        cur_file_flag = true
        cur_files.each do |month_file|
          if month_file.include?("#{filename}")
            cur_file_flag =false
          end
        end
        if cur_file_flag
          conn.putbinaryfile(local_file,"/platform_tools/document/"+CGI::unescape(filename))
        end
      end if File.exists?(local_file)
      File.delete(path)
      return CGI::unescape(filename)
    end
  end

 

private
Directory = "/public/upload/"
def document_params
params.require(:document).permit(:title,:brief_introduction,:detail_introduction,:status,:file)
end
 
  

这样就可以简单实现文档的上传操作了。

我这里数据库中保存的是上传文件的文件名,同样你也可以保存文件路径、文档类型之类的,不过我这里不需要,所以没有实现。

 

转载于:https://www.cnblogs.com/x123811/p/7093375.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值