Image Uploading in Ruby


/ Published in: Ruby
Save to your folder(s)

Checks to make sure the file is a valid image file, checks max file size, and directory write permissions, requires 'fileutils' gem.


Copy this code and paste it in your HTML
  1. def do_image_upload(theFile)
  2. # You should reall set these two in a config.
  3. maxFilesize = 10485760
  4. fileDir = "public/files"
  5.  
  6. fileName = Time.now.to_i.to_s + '-' + rand(36**8).to_s(36) + File.extname(theFile[:filename])
  7. filePath = File.join(fileDir, fileName)
  8.  
  9. tempFile = theFile[:tempfile]
  10.  
  11. upload = {
  12. :fileSize => tempFile.size,
  13. :originalFileName => theFile[:filename],
  14. :fileType => theFile[:type],
  15. :fileName => fileName,
  16. :filePath => filePath
  17. }
  18.  
  19. if upload[:fileType] != 'image/png' && upload[:fileType] != 'image/jpeg' && upload[:fileType] != 'image/gif'
  20. return {'fileError' => 'FileType not allowed.'}
  21. end
  22. if upload[:fileSize] > maxFileSize
  23. return {'fileError' => 'FileSize too large.'}
  24. end
  25.  
  26. if !File.directory?(fileDir)
  27. return {'fileError' => 'Destination ' + directory + ' does not exist.'}
  28. end
  29.  
  30. if !File.writable?(fileDir)
  31. return {'fileError' => 'Cannot write to ' + directory + '.'}
  32. end
  33.  
  34. File.open(filePath, "wb") { |f| f.write(tempFile.read) }
  35.  
  36. return upload
  37. end

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.