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
 
         

這樣就可以簡單實現文檔的上傳操作了。

我這里數據庫中保存的是上傳文件的文件名,同樣你也可以保存文件路徑、文檔類型之類的,不過我這里不需要,所以沒有實現。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM