简体   繁体   English

如何在Laravel 5.2中上传图像

[英]How to upload image in laravel 5.2

This is my form 这是我的表格

@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

This is my controller method 这是我的控制器方法

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

when i upload image and submit image than in the database column field save this image address "/tmp/phpFFuMwC"; 当我上传图像并提交图像时,比在数据库列字段中保存该图像地址“ / tmp / phpFFuMwC”;

That' s because you are saving the temporarily generated file url. 那是因为您要保存临时生成的文件URL。

For files you need to manually save it to the desired location ( make sure it passes validations ): 对于文件,您需要手动将其保存到所需位置(确保其通过验证):

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

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

and then store the new filename ( with or without the path ) in the database something like this: 然后将新文件名(带有或不带有path)存储在数据库中,如下所示:

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

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

On your controlller make these changes 在您的控制器上进行这些更改

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.');
}

Don't forget to use 别忘了使用

use Illuminate\Http\Request;

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

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