你好,我想通过 laravel 上传图像。但我收到此错误消息:
Call to a member function getClientOriginalExtension() on string
我把我的代码放在下面,非常感谢您解决这个问题。
我搜索了这个问题,大多数人说我应该添加 enctype="multipart/form-data" 但我的表单中确实有这个属性。
这是我的代码
我的Product.blade.php:
<form action="{{url('/addProduct')}}" mathod="POST" class="forms-sample" enctype="multipart/form-data">
@csrf
<div class="form-group">
<label for="exampleInputUsername1">title</label>
<input type="text" class="form-control" name="title" id="exampleInputUsername1" placeholder="name of product">
</div>
<div class="form-group">
<label for="exampleInputUsername1">description</label>
<textarea type="text" class="form-control" name="description" id="exampleInputUsername1" placeholder="description of product"></textarea>
</div>
<div class="form-group">
<label for="exampleInputUsername1">price</label>
<input type="text" class="form-control" name="price" id="exampleInputUsername1" placeholder="price of product">
</div>
<div class="form-group">
<label for="exampleInputUsername1">discount price</label>
<input type="text" class="form-control" name="discountprice" id="exampleInputUsername1" placeholder="discount price of product">
</div>
<div class="form-group">
<label for="exampleInputUsername1">quantity</label>
<input type="text" class="form-control" name="quantity" id="exampleInputUsername1" placeholder="quantity of product">
</div>
<div class="form-group">
<label for="exampleFormControlSelect1">category</label>
<select class="form-control form-control-lg" name="category" id="exampleFormControlSelect1">
@foreach($category as $cat)
<option value="{{$cat->category_name}}">{{$cat->category_name}}</option>
@endforeach
</select>
</div>
<input type="file" name="image" class="file-upload-default">
<input type="submit" class="btn btn-primary mr-2">Submit</input>
<button class="btn btn-dark">Cancel</button>
</form>
我的控制器:
use App\Models\Category;
use App\Models\Product;
.
.
.
public function addProduct(Request $request)
{
$product=new product;
$product->title=$request->title;
$product->description=$request->description;
$product->category=$request->category;
$product->quantity=$request->quantity;
$product->price=$request->price;
$product->discount_price=$request->discountprice;
$image= $request->image;
$imagename=time().'.'.$image->getClientOriginalExtension();
$request->image->move('product', $imagename);
// $product->image=$imagename;
$product-> save();
return redirect()->back()->with('message', 'محصول با موفقیت افزوده شد');
}
我的 web.php 文件:
route::get('/addProduct', [AdminController::class, 'addProduct']);
我无法找出我的代码有什么问题,因为当我检查其他教程时没有区别。
你需要使用file()方法
$image= $request->file('image');
$imagename=time().'.'.$image->getClientOriginalExtension();
$request->image->move('product', $imagename);