问题描述
我很难让Auth用户下载laravale存储中的存储文件。用户在表users
的字段id_message
中具有唯一的文件夹名称,用户可以在该文件夹中下载文件。
在AuthController
中如何控制dashboard.blade
才能访问用户下载文件?问题是如何从表变量id_message
添加到file path
文件已存储/app/files/{id_message}/*.zip
return response()->download(store_path('app/files/'.(Auth()->user()->id_message).'/*.zip'));
最后,刀片中将会有什么
<td><a href="{{ }}">Download</a></td>
不明白为什么这个问题很难为我解决。
解决方法
要创建下载链接,(请参见docs)
$filepath = app_path() . '/files/' . Auth::user()->id_message . '/*.zip'
if(\Illuminate\Support\Facades\File::exists($filepath)){
return response()->download($filepath,'your_filename',[
'Content-Length: '. filesize($filepath)
]);
}else{
return false; //you can show error if it returns false
}
在刀片中,只需调用url(get方法)
<td><a href="{{ url('download/' . auth->user()->id_message) }}"
target="_blank">Download</a></td>
,
您可以简单地使用带有文件url的<a>
标签作为标签的href
。
<a href="{{ storage_path('app/files/'.auth()->user()->id_message.'/file.zip') }}" title="Download" target="_blank">
<button class="btn btn-success">Download</button>
</a>
或者您可以使用控制器方法来实现。
路线
Route::get('download-my-file','MyController@downloadZipFile')->name('downloadZipFile');
控制器
public function downloadZipFile()
{
$fileName = storage_path('app/files/'.auth()->user()->id_message.'/file.zip');
return response()->download($fileName);
//you can add file name as the second parameter
return response()->download($fileName,'MyZip.zip');
//you can pass an array of HTTP headers as the third argument
return response()->download($fileName,'MyZip.zip',['Content-Type: application/octet-stream','Content-Length: '. filesize($fileurl))]);
//you can check for file existence.
if (file_exists($fileName)) {
return response()->download($fileName,'MyZip.zip');
} else {
return 0;
}
}
在视野中
<a href="{{ route('downloadZipFile') }}" target="_blank">
<button class="btn btn-success">Download</button>
</a>