Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send an array of files using FormData?

In the backend in laravel I have a field called "file_ticket" and I need to send an array that contains files sent through an input file, I use vue js in the frontend. How can I send this array to my backend? When I try to send only the array, the request returns something like "object file"

result image

onChange(e) {
  let getFiles = [...this.$refs.file.files]
  
  if(!getFiles) return
  ([...getFiles]).forEach(f => {
    this.filelist.push(f)
  })      
},


saveTicket(event){
  event.preventDefault()      
               
  let frmData =  new FormData()
  frmData.append('subject', this.newTicket.subject) 
  frmData.append('service', this.newTicket.service) 
  frmData.append('description', this.newTicket.description)       
  frmData.append('file_ticket', this.filelist)       
  frmData.append('client_id', this.idUser) 


  const url = `ticket/new_ticket`

  axios.post(url, frmData).then((response) => {
    console.log(response)
  })
like image 1000
Mark Avatar asked Mar 10 '26 10:03

Mark


2 Answers

Just append all the files in filelist to formdata using the same key, it will send an array of files.

this.filelist.forEach((file) => {
    frmData.append('file_ticket', file);
});
like image 76
Mythos Avatar answered Mar 11 '26 23:03

Mythos


Instead of appending your files to another array as done in the question append directly but with added square brackets.

Instead of using this:

this.filelist.push(f)

just append the file to the form data object like this:

 frmData.append('file_ticket[]', file);

In your Laravel controller just use this code to take your files (I assume you're using POST and you're passing the Request object as your parameter to your controller function)

if ($request->hasFile('file_ticket')) {
   $file_tickets = $request->file('file_ticket');
   foreach ($file_tickets as $index => $file_ticket) {
      //The rest of your code goes here
   }
}

The hasFile function checks if your request has that file ticket and the $request->file is used to get the array of files.

like image 29
Default Avatar answered Mar 12 '26 00:03

Default