Skip to content

Instantly share code, notes, and snippets.

@abdasis
Created April 30, 2023 00:08
Show Gist options
  • Save abdasis/743111912cf31ea035f52282b036f9d8 to your computer and use it in GitHub Desktop.
Save abdasis/743111912cf31ea035f52282b036f9d8 to your computer and use it in GitHub Desktop.
Livewire component PHP
const filesSelector = document.querySelector('#myFiles');
let awalChunk = [];
filesSelector.addEventListener('change', () => {
const fileList = [...filesSelector.files];
fileList.forEach((file, indeks) => {
@this.set('uploads.' + indeks + '.fileName', file.name);
@this.set('uploads.' + indeks + '.fileSize', file.size);
@this.set('uploads.' + indeks + '.progress', 0);
awalChunk[indeks] = 0;
uploadChunk(indeks, file);
});
});
function uploadChunk(indeks, file) {
// Akhir dari chunk adalah awal + chunkSize ATAU ukuran file, mana yang lebih besar
const akhirChunk = Math.min(awalChunk[indeks] + @js($chunkSize), file.size);
const chunk = file.slice(awalChunk[indeks], akhirChunk);
@this.upload('uploads.' + indeks + '.fileChunk', chunk, (n) => {}, () => {}, (e) => {
if (e.detail.progress == 100) {
awalChunk[indeks] = Math.min(awalChunk[indeks] + @js($chunkSize), file.size);
if (awalChunk[indeks] < file.size) {
let _time = Math.floor((Math.random() * 2000) + 1);
console.log('sleeping ', _time, 'sebelum mengunggah chunk berikutnya');
setTimeout(uploadChunk, _time, indeks, file);
}
}
});
}
public function updatedUploads($value, $key)
{
list($index, $attribute) = explode('.', $key);
if ($attribute == 'fileChunk') {
$fileDetails = $this->uploads[intval($index)];
// File Akhir
$fileName = $fileDetails['fileName'];
$finalPath = \Storage::path('/livewire-tmp/' . $fileName);
// File Chunk
$chunkName = $fileDetails['fileChunk']->getFileName();
$chunkPath = \Storage::path('/livewire-tmp/' . $chunkName);
$chunk = fopen($chunkPath, 'rb');
$buff = fread($chunk, $this->chunkSize);
fclose($chunk);
// Gabungkan file
$final = fopen($finalPath, 'ab');
fwrite($final, $buff);
fclose($final);
unlink($chunkPath);
// Progress
$curSize = \Storage::size('/livewire-tmp/' . $fileName);
$this->uploads[$index]['progress'] = $curSize / $fileDetails['fileSize'] * 100;
if ($this->uploads[$index]['progress'] == 100) {
$this->uploads[$index]['fileRef'] = TemporaryUploadedFile::createFromLivewire(
'/' . $fileDetails['fileName']
);
}
$this->file = $finalPath;
$this->nama_file = $fileName;
$this->ukuran = $this->formatBytes($curSize);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment