I have a backend which handles various actions with pdfs, one of them - combining multiple pdfs into a single one.
The scenario is as follows:
return response()->file(realpath($pathToFile), ['Content-Disposition' => 'inline; filename="'.$file,'Content-Type' => 'application/pdf']);
What I need to do is open this received file in a new window as inline pdf preview but I must have it named (I've tried using blobs but there's no option to provide a title) so that when user clicks on the "download" button of the pdf viewer, they get a named download, which is named by the list title. Sounds like a pretty basic task but I can't find any proper solutions on how to achieve this. Providing url to a file instead of a file response is also not an option because users are only allowed to download their lists and they should not be able to retrieve these files directly by url.
I managed to solve my issue by a walkaround, which is probably not the most optimal solution and feels a bit hack-ish but that's the only solution that worked for me.
I created two routes on my API backend:
1st route
Route::post('/download-file', 'PdfProcessController@downloadFileApi');
Accepts file id
as a parameter. downloadFileApi
method checks if user has access to the needed file, if they do, issue a token using Sanctum
as so $token = Auth::user()->createToken('access_file_token');
lastly, this method returns url, which is a call to the second API route using the generated token return sprintf('%s/api/download-file/%s?_token=%s', env('APP_URL'), $request->input('id'), $token->plainTextToken);
2nd route Route::get('/download-file/{hash}', 'PdfProcessController@downloadFile')->middleware(['token.to.header', 'auth:sanctum']);
The token.to.header
middleware is implemented based on this answer Autheticate via Laravel Sanctum by passing token as a GET query parameter Inside downloadFile
token is destroyed (because it has been used) and an inline pdf is returned.
On my front-end I do
this.$axios.post('/api/download-file', {id: fileid})
.then(response => {
window.open(response.data, '_blank');
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.