'How can I pass an image with array in vue axios post?

  1. Here I push the data of the form into an array with image.
this.tableData.push({
  sub_group: this.items.subGroup,
  amount: this.items.amount,
  item_name: this.items.item_name,
  quantity: this.items.quantity,
  category: this.items.category,
  name: this.items.name,
  image: this.items.image,
});
  1. In the below code I am passing the array of data(this.tableData) which consists of image too but when I stringify it I get only the path empty. If I dont stringyfy it I get the result as [object object]. How can I resolve it?
submitForm(formName) {
  let formdata= new FormData();
  formdata.append('value[]',JSON.stringify(this.tableData));
  console.log(this.tableData);
  axios.post('/api/save-menu', formdata, {
      headers: {
          'accept': 'application/json',
          'Content-Type': 'multipart/form-data'
      }
  }).then(response => {
      this.$notify({
          title: 'Success',
          message: response.data.message,
          type: 'success'
      });
  });
}
  1. After Json.stringify in server-side I get data as
"value" => array:1 [
    0 => "[{"sub_group":1,"amount":"Bert Crosby","item_name":"Brody York","quantity":"Belle Jordan","category":"Corporis sequi bland","name":"Cheryl Dunlap","image":{"$path":""}}]"
  ]
  1. Without Json.Stringify I get the data as
"value" => array:1 [
  0 => "[object Object]"
] 


Solution 1:[1]

you can use object-to-formdata npm module to create the right FormData for transfer. You can't use JSON.stringify because JSON doesn't have File type and your file was lost. Here is a link about types that you can transfer with JSON.

Solution 2:[2]

First of all. Use correct type in your form. <input type="file">

Then you have multiple ways to fetch the image. (FormData Object or File Object).

As FormData:

let form = new FormData();
  files.forEach(file => {
    form.append(file.name, file);
  });
axios.post(url, form);

You can send as File Object (Blob). https://developer.mozilla.org/en-US/docs/Web/API/File

const imageFile = File("your-image.ext");
axios.post(url, imageFile, {
  headers: {
    'Content-Type': imageFile.type
  }
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ruslan Hryshyn
Solution 2 Maik Lowrey