实现把文件上传到服务器,文件名/文件大小/文件的描述 上传到数据库
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代码:
<script language="javascript">
HTMLElement.prototype.insertAdjacentHTML=function(where, html)
{
var e=this.ownerDocument.createRange();
e.setStartBefore(this);
e=e.createContextualFragment(html);
switch (where)
{
case 'beforeBegin': this.parentNode.insertBefore(e, this);break;
case 'afterBegin': this.insertBefore(e, this.firstChild); break;
case 'beforeEnd': this.appendChild(e); break;
case 'afterEnd':
if(!this.nextSibling) this.parentNode.appendChild(e);
else this.parentNode.insertBefore(e, this.nextSibling); break;
}
}
function addText() {
var str ='<input id="file1" name="file[]" size="30" type="file" /></br> <input type="text" id="uploadfile_description" name="uploadfile[]"></br>';
document.getElementById('MyFile').insertAdjacentHTML("beforeEnd",str);
}
</script>
<%=start_form_tag ({:action=>"upload"},:multipart=>true )%>
<div id="MyFile">
<input id="file" name="file[]" size="30" type="file" /></br>
<input type="text" id="uploadfile_description" name="uploadfile[]"></br>
</div>
<input type="button" value="add" onclick="addText()"/>
<input style="cursor:pointer" type="submit" value="upload"/>
<%=end_form_tag%>