<?php

namespace App\Http\Controllers\Mounting;

use App\Http\Controllers\Controller;
use App\Services\DownloadService;
use Illuminate\Http\Request;

class DownloadsController extends Controller
{

    /**
     * 下载文件
     *
     * @param int $fileID
     *
     * @param Request $request
     * @return void ;
     */
    public function downloadFile(int $fileID, Request $request) {
        $file = (new DownloadService())->find($fileID);
        $sessionToken = $request->get('session_token');
        if ($file) {
            $filePath = $file->file_path;
            //检查文件是否存在
            if (! file_exists ( $filePath )) {
                header('HTTP/1.1 404 NOT FOUND');
            } else {
                $downloadInfo = [];
                $downloadInfo['uid'] = $sessionToken->uid;
                $downloadInfo['download_time'] = '';
                $downloadInfo['file_id'] = $file->id;
                (new DownloadService())->downloaded($file, $downloadInfo);

//                return response()->download(storage_path($filePath)); //laravel标准做法
                //以只读和二进制模式打开文件
                $file = fopen ( $filePath, "rb" );

                //告诉浏览器这是一个文件流格式的文件
                Header ( "Content-type: application/octet-stream" );
                //请求范围的度量单位
                Header ( "Accept-Ranges: bytes" );
                //Content-Length是指定包含于请求或响应中数据的字节长度
                Header ( "Accept-Length: " . filesize ( $filePath ) );
                //用来告诉浏览器，文件是可以当做附件被下载，下载后的文件名称为$file_name该变量的值。
                Header ( "Content-Disposition: attachment; filename=" . $file->file_name);

                //读取文件内容并直接输出到浏览器
                echo fread ( $file, filesize ( $filePath ) );
                fclose ( $file );
            }
        } else {
            header('HTTP/1.1 404 NOT FOUND');

            return ;
        }
    }


}
