data_files_controller.rb 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. class DataFilesController < ApplicationController
  2. before_action :set_file, only: [:download, :destroy]
  3. before_action :check_can_download, only: [:download]
  4. before_action :check_can_destroy, only: [:destroy]
  5. def create
  6. uploaded_io = params[:data_file][:data]
  7. @file = DataFile.new(file_params)
  8. @file.uuid = SecureRandom.uuid
  9. @file.name = uploaded_io.original_filename
  10. if uploaded_io.size > 100.megabytes
  11. flash[:danger] = "File too large (>100MB)"
  12. redirect_to @file.repository
  13. return
  14. end
  15. unless @file.repository.can_upload_files?(current_user)
  16. redirect_to root_url
  17. return
  18. end
  19. Dir.mkdir Rails.root.join('public', 'uploads', @file.uuid)
  20. File.open(Rails.root.join('public', 'uploads', @file.uuid, uploaded_io.original_filename), 'wb') do |file|
  21. file.write(uploaded_io.read)
  22. end
  23. flash[:danger] = "Error creating file" unless @file.save
  24. redirect_to @file.repository
  25. end
  26. def download
  27. send_file @file.file_path
  28. end
  29. def destroy
  30. @file.destroy
  31. redirect_to @file.repository
  32. end
  33. private
  34. def set_file
  35. @file = DataFile.find(params[:id])
  36. end
  37. def file_params
  38. params.require(:data_file).permit(:repository_id, :repository_type)
  39. end
  40. def check_can_download
  41. redirect_to root_url unless @file.repository.can_download_files?(current_user)
  42. end
  43. def check_can_destroy
  44. redirect_to root_url unless @file.repository.can_upload_files?(current_user)
  45. end
  46. end