将上传的图像发送到视图并在img标记内显示

时间:2016-02-07 13:23:23

标签: php laravel file-upload

我是Laravel的新手,正在使用图片上传机制。我成功上传并验证了图片,但无法弄清楚如何发送图片以显示。

我有一个名为userController的控制器。在resource/views/user目录中,我有以下三个刀片模板,它们是:

  1. index.blade.php

  2. create.blade.php

  3. store.blade.php

  4. 我在create.blade.php内有我的PHP表单。提交表单后,我想将上传的图片发送到index.blade.php。怎么能实现这个?

    userController的store()方法:

     public function store(Request $request)
        {
            //
            $data = Input::all();
    
    
    
            $rules = array(
               'name' => 'unique:users,name|required|alpha_num',
               'password'=>'required',
               'image' => 'mimes:jpeg,jpg,png,gif|required|max:100'
            );
    
            // Create a new validator instance.
            $validator = Validator::make($data, $rules);
            if($validator->fails()){
    
                $errors=$validator->messages();
                return Redirect::route('user.create')->withErrors($validator);
    
            }else{
    
                if(Input::hasFile('image')){
                    $file=Input::file('image');
                    $file->move('uploads',$file->getClientOriginalName());
                    return Redirect::route('user.index')->with(file); // tried this but don't know whether it will work or not 
                }
    
            }
    
        }
    

    index.blade.php页面

    <!DOCTYPE html>
    <html>
    
    <body>
      // i want to show the uploaded image here
    
    <h1>Hi this is index </h1>
    <a href="{{ URL::to('user/create') }}">Create a task</a>
    
    </body>
    </html>
    

1 个答案:

答案 0 :(得分:0)

在退货声明之前,

$image = $file->getClientOriginalName() . '.' . $file->getClientOriginalExtention(); 

Session::flash('image', 'uploads/' . $image); 

return Redirect::route('user');

并在

Public function index()
{
   If(Session::has('image'))
    {
       return view('user.index')->with(compact('image'));
     }
}

在您的头部索引刀片文件中

<img src="{!!$image!!}">