Reputation: 163
I have difficulty understanding the file save and retrieval in Laravel. I managed to get the file saved into correct path
$fileNameWithExt = $request->file('Agreement_file')->getClientOriginalName();
$fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extention =$request->file('Agreement_file')->getClientOriginalExtension();
$filenameToStore = $fileName . '_' . $lab_id. '.'.$extention;
$request->Agreement_file->storeAs('agreements', $filenameToStore );
However not I want to create an a-tag to download the file, but cannot manage to get to download the file.
<a href="/storage/app/public/agreements/'. {{$filenameToStore}}" download="{{$filenameToStore}}">{{$filenameToStore}}</a>
The file download but I get the error "Failed- Server Problem". I do not want to use a same link as these files are confidential and should not be able to be downloaded outside the app.
Upvotes: 1
Views: 3619
Reputation: 2683
Something like that?
Step 1:
Create table files id | filename | user_id
.
Step 2:
Create model File
Step 3:
Add file row in table.
$fileNameWithExt = $request->file('Agreement_file')->getClientOriginalName();
$fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extention =$request->file('Agreement_file')->getClientOriginalExtension();
$filenameToStore = $fileName . '_' . $lab_id. '.'.$extention;
$request->Agreement_file->storeAs('agreements', $filenameToStore );
File::create([
'filename' => $filenameToStore,
'user_id' => Auth::id()
]);
Step 4:
Create controller method download.
public function download(){
$filename = $request->input('filename');
$file = File::where('user_id', Auth::id())
->where('filename', $filename)
->firstOrFail();
$path = Storage::path('agreements/' . $filename);
if(Storage::exists($path)){
return Response::download($path, $filename);
}
}
Step 5:
Replace your link:
<a href="/path/download?filename='. {{$filenameToStore}}" download="{{$filenameToStore}}">{{$filenameToStore}}</a>
Or you can build it based on the file ID.
Upvotes: 1