I am currently working on a form where users can upload one or more photos to the server using ajax. Sometimes, users may not upload any photos at all. How can I efficiently send the data from the file input to the server in the background?
Below is the relevant section of the form:
<form action="" method="POST" enctype="multipart/form-data>
@csrf
<label for="photos">Photos:</label>
<input type="file" name="photos[]" id="photos" class="form-control" multiple>
<button class="btn btn-success mt-3" onclick="ajaxify(event)">Submit</button>
</div>
</form>
And here is the relevant part of the JavaScript code:
function ajaxify(event) {
event.preventDefault();
let failedValidation = false;
// Some parts of this code have been omitted for clarity.
let photos = [];
if(document.getElementById('photos').value !== '') {
photos = document.getElementById('photos'); // This part needs correction.
}
// The current implementation only returns one file path like c://fake/filename,
// and it does not handle multiple file uploads correctly.
if(!failedValidation) {
axios.post('/listing/create', {
client_name: name.value,
// Other data fields omitted for brevity.
photos: photos.value, // Incorrect handling of uploaded files.
})
.then((resp) => {
invalid.classList.add('d-none');
console.log(resp);
})
}
}
Goal: My objective is to have the uploaded files available to Laravel on the server side so that I can process them with a normal post request and retrieve the array of uploaded files using dd($request->photos);
. I am not sure if this functionality can be achieved using ajax/json, but it would greatly help in processing the photos.
A quick note, I am utilizing the Laravel media library package for this project.
Progress: Upon researching, I found suggestions to use FormData(). However, I have some questions regarding its usage. Should all data be included in the FormData() object and passed to axios? Or is it specifically required for handling photos? I have yet to implement either approach and would appreciate any guidance on this matter.