表单上传一些文本和图片,下面是控制器代码,如果有图片上传,可以正常跑通,但测试如果不上传图片,会重定向到首页,说好的报错不知道报到哪里去了。
public function store(Requests\StoreArticlePostRequest $request)
{
$article = new Article($request->except('image'));
$article->user_id = \Auth::id();
if ($request->hasFile('image')) {
$file = $request->file('image');
$allowed_extensions = ["png", "jpg"];
if ($file->getClientOriginalExtension() && !in_array($file->getClientOriginalExtension(), $allowed_extensions)) {
return ['error' => '图片格式只能为png、jpg'];
}
$extension = $file -> getClientOriginalExtension();
$fileName = \Auth::user()->id . '_' . time() . '.' . $extension;
$destinationPath = 'uploads/' . $article->user_id . '/';
$file->move($destinationPath, $fileName);
$article->picture = $fileName;
$article->save();
} else {
echo "必须上传图片";
}
return redirect()->action('PostsController@show', ['id' => $article->id]);
}