我根据文件上传和下载制作应用。目前,使用AJAX下载文件时,我会获取要下载的文件的名称,将其传递给服务器端并返回我追加到html <a></a>
标记的路径。
public function downloadUserFile(){
mb_internal_encoding('UTF-8');
$ds = DIRECTORY_SEPARATOR;
$userid = Auth::id();
$filename = htmlspecialchars_decode($_POST['filename']);
$entry = File::where('filename', $filename)->firstOrFail();
$onlyFilename = substr($filename, 0, strrpos($filename, "."));
$type = \Illuminate\Support\Facades\File::extension(storage_path().'uploads'.$ds.$userid.$ds.$filename);
$filenameVersion = $onlyFilename.'_0'.'.'.$type;
$file = Storage::disk()->get('uploads'.$ds.$userid.$ds.$filenameVersion);
$path = $userid.'/'.$filenameVersion;
$arr = array('path' => $path, 'filename' => $filename);
return json_encode($arr);
}
我也看到人们使用readfile()
或response()->download()
(虽然我仍然无法理解如何使用response()-download()
)。那么实现文件下载逻辑的最佳方法是什么?