rails实现多文件的上传

实现把文件上传到服务器,文件名/文件大小/文件的描述 上传到数据库


Application.rb代码如下:

# Filters added to this controller apply to all controllers in the application.

# Likewise, all the methods added will be available for all controllers.



class ApplicationController < ActionController::Base

# Pick a unique cookie name to distinguish our session data from others'

session :session_key => '_uploadF_session_id'



def uploadFile(file)

if !file.original_filename.empty?

@filename=getFileName(file.original_filename)

File.open("#{RAILS_ROOT}/public/files/#{@filename}", "wb") do |f|

f.write(file.read)

end

return @filename

end

end



def getFileName(filename)

if !filename.nil?

return filename

end

end



def savefiles(file,description)

@filename=getFileName(file.original_filename)

@filesize=getFileName(file.length)

@uploadfile = Uploadfile.new

@uploadfile.filename=@filename

@uploadfile.filesize=@filesize/1024

@uploadfile.description=description

@uploadfile.save

end

end


upload_controller.rb代码如下:

class UploadController < ApplicationController

def upload

@uploadfile = Uploadfile.new

unless request.get?

i=params[:file].size

for num in (0..i-1)

if filename=uploadFile(params[:file][num])

savefiles(params[:file][num],params[:uploadfile][num])

end

end

end

end

end



upload.rhtml代码:



<%=start_form_tag ({:action=>"upload"},:multipart=>true )%>















<%=end_form_tag%>

你可能感兴趣的:(ROR)