Commit 70cd4f75 by Ivan Lan

Create Chunkfile

parent 56573d1e
class CreateChunkFiles < ActiveRecord::Migration[5.1]
def change
create_table :chunk_files do |t|
t.integer :chunk_number, comment: '文件块数,从1开始'
t.integer :chunk_size, comment: '文件块的大小'
t.integer :current_chunk_size, comment: '当前文件块的大小'
t.integer :total_size, comment: '文件总大小'
t.string :identifier, comment: '文件标识'
t.string :filename, comment: '文件名'
t.integer :total_chunks, comment: '文件块的总个数'
t.timestamps
end
end
end
# == Schema Information
#
# Table name: chunk_files
#
# id :bigint not null, primary key
# chunk_number(文件块数,从1开始) :integer
# chunk_size(文件块的大小) :integer
# current_chunk_size(当前文件块的大小) :integer
# total_size(文件总大小) :integer
# identifier(文件标识) :string(255)
# filename(文件名) :string(255)
# total_chunks(文件块的总个数) :integer
# created_at :datetime not null
# updated_at :datetime not null
#
module Whaleback
class ChunkFile < ApplicationRecord
LocalPath = './public/chunk_file'.freeze
attr_accessor :io
after_save :write_file
def folder
File.join(ChunkFile::LocalPath, identifier)
end
def file_path
File.join(folder, filename)
end
def chunk_file_path
File.join(folder, "#{filename}.part#{chunk_number}")
end
def uploading_file_path
File.join(floer, "#{filename}.part#{chunk_number}.loading")
end
def all_finish?
finish_indexs = Dir['./*.part?'].map { |path| /.part(\d+)/.match(path)[1] }.sort
finish_indexs == (1..total_chunks)
end
def finish_loading
File.rename(uploading_file_path, chunk_file_path)
end
private
def write_file
FileUtils.mkdir_p folder
File.open(uploading_file_path, 'wb') do |file|
file.write(@io)
end
finish_loading
merge_file if all_finish?
end
def merge_file
FileUtils.remove file_path, force: true
(1..chunk_number).each do |index|
File.open(filepath, 'ab') do |file|
file.write File.open("#{file_path}.part#{index}", 'rb').read
end
end
save_attachment
end
def save_attachment filepath
mime_type = Rack::Mime.mime_type(File.extname(filepath))
case mime_type
when /^image/
attachment = Image.new
when /^video/
attachment = Video.new
else
attachment = Document.new
end
attachment.file = File.open(filepath, 'rb')
attachment.creator = current_auth
attachment.save!
end
end
end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment