我想用laravel上传图片:我在mysql中创建了字段:
imagepath varchar 250
创建表单:
<form method="post" id="formId" action="/ticket" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group ">...other fields
<div class="form-group">
<input type="file" class="form-control-file" name="imageFile" id="imageFile" aria-describedby="fileHelp">
</div>
在我的控制器中:
public function store(Request $request)
{
$fileName = request()->imageFile->getClientOriginalExtension();
dd($fileName);//echos ".jpg"
$tickes = Users::create(['imagePath' => $fileName]);
}
但是我的db总是为null!我想将它存储在Laravel的public / storage文件夹中。 请帮忙!
答案 0 :(得分:2)
您可以使用此代码将图像上传到`public / storage / directory:
if ($request->hasFile('input_img')) {
if($request->file('input_img')->isValid()) {
try {
$file = $request->file('input_img');
$name = rand(11111, 99999) . '.' . $file->getClientOriginalExtension();
# save to DB
$tickes = Users::create(['imagePath' => 'storage/'.$name]);
$request->file('input_img')->move("storage", $name);
} catch (Illuminate\Filesystem\FileNotFoundException $e) {
}
}
}
答案 1 :(得分:0)