Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chunk upload follow up 2 #6957

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading