繁体   English   中英

如何在Laravel 5.2中上传图像

[英]How to upload image in 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');
}

当我上传图像并提交图像时,比在数据库列字段中保存该图像地址“ / tmp / phpFFuMwC”;

那是因为您要保存临时生成的文件URL。

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

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

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

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

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

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

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

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM