diff --git a/app/controllers/hyrax/uploads_controller.rb b/app/controllers/hyrax/uploads_controller.rb index a18b1c1044..fb8ad050f8 100644 --- a/app/controllers/hyrax/uploads_controller.rb +++ b/app/controllers/hyrax/uploads_controller.rb @@ -1,16 +1,15 @@ # frozen_string_literal: true - module Hyrax class UploadsController < ApplicationController load_and_authorize_resource class: Hyrax::UploadedFile def create if params[:id].blank? - handle_new_upload + @upload.attributes = { file: params[:files].first, + user: current_user } else - handle_chunked_upload + upload_with_chunking end - @upload.save! end @@ -21,43 +20,24 @@ def destroy private - def handle_new_upload - @upload.attributes = { file: params[:files].first, user: current_user } - end + def upload_with_chunking + @upload = Hyrax::UploadedFile.find(params[:id]) + unpersisted_upload = Hyrax::UploadedFile.new(file: params[:files].first, user: current_user) - def chunk_valid?(upload) + # Check if CONTENT-RANGE header is present content_range = request.headers['CONTENT-RANGE'] - return false unless content_range - - begin_of_chunk = content_range[/\ (.*?)-/, 1].to_i - current_size = upload.file.size - - upload.file.present? && begin_of_chunk == current_size - end + return @upload.file = unpersisted_upload.file if content_range.nil? - def handle_chunked_upload - @upload = Hyrax::UploadedFile.find(params[:id]) - unpersisted_upload = Hyrax::UploadedFile.new(file: params[:files].first, user: current_user) + # deal with chunks + current_size = @upload.file.size + begin_of_chunk = content_range[/\ (.*?)-/, 1].to_i # "bytes 100-999999/1973660678" will return '100' - if chunk_valid?(@upload) - append_chunk(@upload) + # Add the following chunk to the incomplete upload + if @upload.file.present? && begin_of_chunk == current_size + File.open(@upload.file.path, "ab") { |f| f.write(params[:files].first.read) } else - replace_file(@upload, unpersisted_upload) - end - end - - def append_chunk(upload) - File.open(upload.file.path, "ab") do |f| - f.write(params[:files].first.read) + @upload.file = unpersisted_upload.file end - - upload.reload - end - - def replace_file(upload, unpersisted_upload) - upload.file = unpersisted_upload.file - upload.save! - upload.reload end end end