I have the following route:
Route::post('report', Controllers\ReportController::class)->name('report');
And the controller loads a file and returns it
$path = '/some/path/to/report.xls';
return response()->download($path);
In a standard Laravel/Blade project, a <form method="post">@csrf</form>
works fine.
In Inertia/vue3 this is my code:
<script setup>
const form = useForm({
some: null,
fields: null,
});
</script>
<form u/submit.prevent="form.post(route('report'))" >
<input v-model="form.some" />
<input v-model="form.fields" />
<button type="submit">download</button>
</form>
Instead of downloading the generated file, the route returns a 302 redirection and the browser refreshes the page. I cannot make a link to the file to be downloaded, as it is generated depending on the data from the form.
What am I doing wrong?
I have the following route:
Route::post('report', Controllers\ReportController::class)->name('report');
And the controller loads a file and returns it
$path = '/some/path/to/report.xls';
return response()->download($path);
In a standard Laravel/Blade project, a <form method="post">@csrf</form>
works fine.
In Inertia/vue3 this is my code:
<script setup>
const form = useForm({
some: null,
fields: null,
});
</script>
<form u/submit.prevent="form.post(route('report'))" >
<input v-model="form.some" />
<input v-model="form.fields" />
<button type="submit">download</button>
</form>
Instead of downloading the generated file, the route returns a 302 redirection and the browser refreshes the page. I cannot make a link to the file to be downloaded, as it is generated depending on the data from the form.
What am I doing wrong?
Share Improve this question asked Nov 19, 2024 at 23:24 StRStR 5609 silver badges20 bronze badges1 Answer
Reset to default 0It may not be exact answer to you question, we don't know what code is inside controller but few things worth checking:
Type of response that comes from ReportController and what headers there are. eg, taken from domPDF we are using in our project: `
public function stream(string $filename = 'document.pdf'): Response
{
$output = $this->output();
return new Response($output, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="'.$filename.'"',
]);
}`
Another solution can be response()->download()
or response()->streamDownload()
Documented here:
https://laravel/docs/10.x/responses#file-downloads
And if the file comes from the API, you might need this too:
https://www.npmjs/package/js-file-download
Lastly, I'm not sure if it's possible to download file same time using useForm helper(haven't tested it myself), so you might need to fallback for router.post()
of axios/fetch
requests.
Cheers.