Problem with file upload

I have a problem with file upload on server. The following code:

def UploadFile(jpg, folder, name)
if (!jpg.nil? and !jpg.local_path.nil? and
FileTest.exists?(jpg.local_path))
if ((‘image/jpeg’ == jpg.content_type.to_s.rstrip) || (‘image/pjpeg’
== jpg.content_type.to_s.rstrip))
unless File.exists?(folder)
FileUtils.mkdir_p(folder)
File.chmod(0750, folder)
end
filename = File.expand_path(File.join(folder, name))
File.unlink(filename) if FileTest.exists?(filename)
! FileUtils.cp_r(jpg.local_path, filename)
File.chmod(0644, filename)
return true
else
return false
end
else
return false
end
end


crashes while trying to load file(usually smaller than 16 Kb, becouse
small files send as StringIO ex: “imgfile”=>#StringIO:0xb77f9e80, but
for big files only link to tmp file sends to server ex:
“imgfile”=>#<File:/tmp/CGI29745.5>). The error occurs on a string
matched by !. Here is error for small file:

NoMethodError (You have a nil object when you didn’t expect it!
The error occured while evaluating nil.to_str):
/usr/local/lib/ruby/1.8/fileutils.rb:1389:in fu_each_src_dest0' /usr/local/lib/ruby/1.8/fileutils.rb:1375:infu_each_src_dest’
/usr/local/lib/ruby/1.8/fileutils.rb:422:in `cp_r’


Could anyone help me with my problem? Storing small images in database
is silly. IMHO of course.