I have a file upload form in vue and want to pass the file data to a laravel controller. The data is passed from page to store fine in vue, but I can't access it in my controller:
vue page:
update() {
this.$store.dispatch('uploadDocument', {
file: this.form.file,
})
},
store:
axios.post('/users/newDocument', {
file: data.file,
})
If I console.log
data.file
, I can see the file is passed to post method:
'File {name: 'test2.txt', lastModified: 1633600501434, lastModifiedDate:......'
Route:
Route::post('/users/newDocument', [UserController::class, 'store']);
controller:
public function store(Request $request)
{
return $request;
}
but nothing is returned, even if I do $request->file
, or $request->hasFile('file')
:
'{data: {…}, status: 200, statusText: 'OK', headers: {…}, config: {…}, …}'
Any ideas what I'm missing? Do I need to first build the form data? (new FormData())
. I've tried adding _method: 'PATCH'
to the form and adding the header: 'Content-Type': 'multipart/form-data'
, but still nothing.
FIX: in vue, pass the form data:
const formData = new FormData();
formData.append('name', this.form.file.name);
formData.append('document_type', this.form.document_type);
in vue store:
axios.post('/users/newDocument', formData, {'content-type': 'multipart/form-data'})
laravel controller:
$request->get('name')
CodePudding user response:
You need to build the FormData first and send it though axios Wwthout forgetting to modify the header as you started to do it.