When making visits that include files (even nested files), Inertia will automatically convert the request data into a FormData
object. This is necessary, since that's what's required to submit a multipart/form-data
request via XHR.
If you'd like the visit to always use a FormData
object, you can force this using the forceFormData
option.
Inertia.post('/users', data, {
forceFormData: true,
})
You can learn more about the FormData
interface here.
FormData
, and you'll need to manually do this.Here is an example of uploading a file with Inertia using a form. This example includes both a name
text input and an avatar
file input.
<template>
<form @submit.prevent="submit">
<input type="text" v-model="form.name" />
<input type="file" @input="form.avatar = $event.target.files[0]" />
<progress v-if="form.progress" :value="form.progress.percentage" max="100">
{{ form.progress.percentage }}%
</progress>
<button type="submit">Submit</button>
</form>
</template>
<script>
import { useForm } from '@inertiajs/inertia-vue3'
export default {
setup () {
const form = useForm({
name: null,
avatar: null,
})
function submit() {
form.post('/users')
}
return { form, submit }
},
}
</script>
This example uses the form helper, since it gives us easy access to the upload progress, but you can do this with a plain Inertia visit as well.
Uploading files using a multipart/form-data
request is not natively supported in some languages for the put
,patch
or delete
methods. The workaround here is to simply upload files using post
instead.
Some frameworks, such as Laravel and Rails, support form method spoofing, which allows you to upload the files using post
, but have the framework handle the request as a put
or patch
request. This is done by including a _method
attribute in the data of your request.
Inertia.post(`/users/${user.id}`, {
_method: 'put',
avatar: form.avatar,
})