/ Published in: Ruby
Checks to make sure the file is a valid image file, checks max file size, and directory write permissions, requires 'fileutils' gem.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
def do_image_upload(theFile) # You should reall set these two in a config. maxFilesize = 10485760 fileDir = "public/files" fileName = Time.now.to_i.to_s + '-' + rand(36**8).to_s(36) + File.extname(theFile[:filename]) filePath = File.join(fileDir, fileName) tempFile = theFile[:tempfile] upload = { :fileSize => tempFile.size, :originalFileName => theFile[:filename], :fileType => theFile[:type], :fileName => fileName, :filePath => filePath } if upload[:fileType] != 'image/png' && upload[:fileType] != 'image/jpeg' && upload[:fileType] != 'image/gif' return {'fileError' => 'FileType not allowed.'} end if upload[:fileSize] > maxFileSize return {'fileError' => 'FileSize too large.'} end if !File.directory?(fileDir) return {'fileError' => 'Destination ' + directory + ' does not exist.'} end if !File.writable?(fileDir) return {'fileError' => 'Cannot write to ' + directory + '.'} end File.open(filePath, "wb") { |f| f.write(tempFile.read) } return upload end