zoukankan      html  css  js  c++  java
  • 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
    
    

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

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

  • 相关阅读:
    oracle新建用户赋权限
    Linux配置tomcat自动启动
    java白皮书关键术语
    sql中exists和not exists的用法
    db2用户、权限相关命令
    面试问题
    能ping通,但是打不开网页
    kali linux的错误
    virtualbox display size
    Jetson tk1 安装 CUDA,ROS,OpenCV和kinect2以及刷机以及ssh远程控制
  • 原文地址:https://www.cnblogs.com/x123811/p/7093375.html
Copyright © 2011-2022 走看看