I played around with image uploads from regular JS, maybe you can use something like it-
function getElement(selector) {
return document.querySelector(selector);
}
async function uploadFiles(e) {
e.preventDefault();
const images = getElement('#images');
let stats = {
noOfImages: images.files.length,
loop: 1,
counter: 0,
maxFiles: 20,
};
while (stats.noOfImages > 0) {
if (stats.noOfImages < stats.maxFiles) {
stats.maxFiles = images.files.length;
stats.loop = 1;
}
let formData = await createFormData(images, stats);
await upload(formData);
stats.noOfImages -= stats.maxFiles;
}
getElement('#images').value = null;
}
async function upload(formData) {
try {
const response = await fetch('/api/uploads', {
method: 'POST',
body: formData
});
const result = await response.json();
displaySuccess(result);
} catch (error) {
displayError(error);
}
}
async function createFormData(images, stats) {
let formData = new FormData();
formData.append('_token', getElement('#_token').value);
formData.append('user_id', getElement('#user_id').value);
for (let i = stats.counter; i < stats.maxFiles * stats.loop; i++) {
formData.append('images[]', images.files[i]);
stats.counter++;
}
stats.loop++;
return formData;
}
What it does, is that it takes the files from a file input, then batch them twenty and twenty to keep the upload size and amount of files allowed inside the limits.
The html
<form action="{{ route('uploads') }}" method="post" enctype="multipart/form-data">
<input type="hidden" name="user_id" value="1" id="user_id">
<input type="hidden" name="_token" id="_token" value="{{ csrf_token() }}" />
<input type="file" name="images[]" id="images" multiple>
<input type="submit" value="Upload" id="submit">
</form>
The php used
public function __invoke(UploadsFormRequest $request)
{
$validData = $request->validated();
$images = $request->file('images');
$imageData['user_id'] = $validData['user_id'];
foreach ($images as $image) {
$imageData['original_name'] = $image->getClientOriginalName();
$imageData['stored_name'] = Str::replace('uploads/', '', $image->store('uploads'));
Upload::create($imageData);
}
ProcessUploadedImagesJob::dispatch($validData['user_id']);
return response()
->json([
'status' => 'Success, your files will be available shortly',
]);
}