Search code examples
phplaraveltemporary-files

How to generate temporary file download url for laravel local storage?


From Laravel official documentation:

For files stored using the s3 or rackspace driver, you may create a temporary URL to a given file using the temporaryUrl method.

Is there any way to have temporary download url for files rather than using s3/etc and for local storage only. I am using https://github.com/spatie/laravel-medialibrary library for development.


Solution

  • public function downloadFileAction()
    {
        if (isset($_REQUEST['file_name'])) {
            $pathFile = STORAGE_PATH.'/'.$_REQUEST['file_name'];
    
            header('Content-Description: File Transfer');
            header('Content-Disposition: attachment; filename="'.$_REQUEST['file_name'].'"');
            header('Content-Type: application/octet-stream');
            header('Content-Transfer-Encoding: binary');
            header('Content-Length: ' . filesize($pathFile));
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Pragma: public');
            header('Expires: 0');
            readfile($pathFile);
        }
    }
    
    
    
    
    public function uploadFile(array $file)
        {
            $storagePath = STORAGE_PATH;
    
            @mkdir($storagePath, 0777, true);
    
            $fullPath = $storagePath. uniqid (time()). $file['name'];
            $fileTemp = $file['tmp_name'];
    
            move_uploaded_file($fileTemp, $fullPath);
    
            return $fullPath;
        }
    

    In your controller, you can take file with this: $_FILES