douchanxiu5636 2014-04-10 15:47
浏览 27

访问公用文件夹之外的文件

I want to store files (pdfs, images, videos) that can only be accessed by Laravel. This would force a user to use the website rather than a url.

How can I achieve this? And are there best practices to doing this?

thank you!

Here is my code:

public static function downloadFile($id){
        $file = FileManager::find($id);
        //$file->location = ../app/storage/file/dam04/2-2/manual.pdf
        //file->type = pdf
        //file->name = instructor manual
        $headers = array(
              'Content-Type:'.mime_content_type($file->location),
            );
        return Response::download($file->location, $file->name.'.'.$file->type, $headers);

        //exit;
     }

I cannot get this to fire. the files are located in app/storage/.

I could really use some advice as to why this won't work. Thanks,

  • 写回答

1条回答 默认 最新

  • dr200166 2014-04-10 16:04
    关注

    You can use Response::download():

    Create a router:

    Route::get('/files/{fileName}', 'FileServerController@download');
    

    And in your controller you do

    class FileServerController extends Controller {
    
        public function download($fileName)
        {
            if (file_exists("$basepath/$fileName"))
            {
                return Response::download("$basepath/$fileName");
            }
    
            return Redirect::route('home')->withMessage('file not found');
    
            // or return Response::make('File not found', 404);
        }
    
    }
    

    You can auth filter your route:

    Route::get('/files/{fileName}', ['before' => 'auth', 'uses' => 'FileServerController@download']);
    

    And you can use intended() to start downloading a file as soon as your user is logged in:

    if (Auth::attempt(...))
    {
       return Redirect::intended('home');
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 科来模拟ARP欺骗困惑求解
  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥15 流式socket文件传输答疑
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)