Skip to content

Commit

Permalink
Merge pull request #6957 from samvera/chunk-upload-follow-up
Browse files Browse the repository at this point in the history
Chunk upload follow up 2
  • Loading branch information
laritakr authored Nov 2, 2024
2 parents 7834acc + ff7aa68 commit ea6f782
Showing 1 changed file with 15 additions and 35 deletions.
50 changes: 15 additions & 35 deletions app/controllers/hyrax/uploads_controller.rb
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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

0 comments on commit ea6f782

Please sign in to comment.