我是Laravel的初学者。我需要上传一张图片,并且该图片需要保存在数据库中,但无法正常工作有人可以看看我的逻辑,看看我要去哪里了吗?
StudentController.php
public function store(Request $request)
{
$this->validateRequest();
// Handle File Upload
if($request->hasFile('cover_image')){
// Get filename with the extension
$filenameWithExt = $request->file('cover_image')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('cover_image')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.'_'.time().'.'.$extension;
// Upload Image
$path = $request->file('cover_image')->storeAs('public/cover_images', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
dd( $fileNameToStore);
$student = new student();
$student->cover_image = $fileNameToStore;
$student->save();
return redirect()->route('show')->with('response', 'Registered Successfully');
}
当dd($ fileNameToStore);它给出的结果为“ noimage.jpg”
create.blade.php
@extends('layouts.app')
@section('content')
<div class="container">
{!! Form::open(['url' => 'student','method' => 'get', 'enctype' => 'multipart/form-data'])!!}
<div class="form-group">
{{Form::file('cover_image')}}
</div>
<button type="submit" class="btn btn-primary">Submit</button>
{!! Form::close() !!}
</div>
@endsection
答案 0 :(得分:0)
请尝试使用此代码
$input = $request->all();
if ($request->hasFile('cover_image')) {
$destinationPath = public_path().'/your path/';
$file = $request->cover_image;
$fileName = time() . '.'.$file->clientExtension();
$file->move($destinationPath, $fileName);
$input['image'] = $fileName;
}
$student = new student();
$student ->create($input);
答案 1 :(得分:0)
@extends('layouts.app')
@section('content')
<div class="container">
{!! Form::open(['url' => 'student','method' => 'post', 'enctype' => 'multipart/form-data'])!!}
<div class="form-group">
{{Form::file('cover_image')}} //name = image
</div>
<button type="submit" class="btn btn-primary">Submit</button>
{!! Form::close() !!}
</div>
@endsection