I’m working on vue3 and I want to send my form data which may contain a file image to my API via axios request but I still have a problem. If I inspect the formData instance, all values are present but are ignored when my axios Content-Type header are set to multipart/form-data. I also use Pinia in my work to store my functions. Can someone help me please?
My Pinia function
async createEnterprise(data) {
const formData = new FormData();
formData.append("logo", data.value.logo, data.value.logo.name);
formData.append("name", data.value.name);
formData.append("email", data.value.email);
formData.append("phone", data.value.phone);
formData.append("address", data.value.address);
try {
const response = await axios.post('/api/auth/entreprises/store', formData, {
headers: {
"Authorization": `Bearer ${localStorage.getItem('token')}`,
"Content-Type": "multipart/form-data",
"Accept": "application/json"
},
data: formData
})
const data = await response.data;
} catch (error) {
this.errors = error.response.data.errors;
}
},
My create view in vue
const data = ref({
name: "",
email: "",
phone: "",
address: "",
logo: null
});
const handleFileChange = (event) => {
let logo = event.target.files[0];
data.value.logo = logo;
}
const submitForm = async () => {
try {
await createEnterprise(data);
} catch (error) {
console.log("Error submitting form: " + error);
}
}
<form @submit.prevent="submitForm">
<div class="create__form__group">
<label for="logo" class="create__label">Logo:</label>
<p class="text-sm opacity-75 indent-3">Cliquer dans le vide pour charger le logo</p>
<label class="create__file__label border border-gray-200 hover:border-4 hover:border-blue-200">
<div class="file__upload__icon">
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
stroke-linejoin="round" class="feather feather-image">
<rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
<circle cx="8.5" cy="8.5" r="1.5"></circle>
<polyline points="21 15 16 10 5 21"></polyline>
</svg>
</div>
<input type="file" accept="image/*" class="focus:outline-none focus:ring focus:ring-blue-200"
@change="handleFileChange">
<p class="file__info">Aucun fichier sélectionné</p>
</label>
<p class="error" v-if="enterprisesStore.errors.logo">{{ enterprisesStore.errors.logo[0] }}</p>
</div>
</form>
When I submit the form, the result of the data still empty with all fields input filled, That means the input fields values are not sent