如何在laravel 5.2中上传图片

时间:2016-06-29 07:26:58

标签: php laravel laravel-5.2

这是我的表格

@extends('layout.template')
    @section('content')
        <h1>Add Student</h1>
        {!! Form::open(array('action' => 'studentController@save', 'files'=>true)) !!}

        <div class="form-group">
            {!! Form::label('Profile-Picture', 'Profile Picture:') !!}
            {!! Form::file('image',null,['class'=>'form-control']) !!}
        </div>

        <div class="form-group">
            {!! Form::submit('Save', ['class' => 'btn btn-primary form-control']) !!}
        </div>
        {!! Form::close() !!}
    @stop

这是我的控制器方法

public function save()
{
    $students=Request::all();
    students::create($students);
    Session::flash('flash_message', 'Record successfully added!');
    return redirect('students');
}

当我上传图片并提交图片时,比在数据库列字段中保存此图片地址&#34; / tmp / phpFFuMwC&#34 ;;

2 个答案:

答案 0 :(得分:0)

这&#39;因为你要保存临时生成的文件网址。

对于文件,您需要手动将其保存到所需位置 (确保它通过验证):

$request->file('photo')->move($destinationPath);

// With a custom filename    
$request->file('photo')->move($destinationPath, $fileName);

然后将新文件名(带或不带路径)存储在数据库中,如下所示:

$students = new Students;
$students->image = $fileName;
...
$students->save();

文档:https://laravel.com/docs/5.2/requests#files

答案 1 :(得分:0)

在您的控制器上进行这些更改

public function save(Request $request)
{
    $destination = 'uploads/photos/'; // your upload folder
    $image       = $request->file('image');
    $filename    = $image->getClientOriginalName(); // get the filename
    $image->move($destination, $filename); // move file to destination

    // create a record
    Student::create([
        'image' => $destination . $filename
    ]);

    return back()->withSuccess('Success.');
}

别忘了使用

use Illuminate\Http\Request;