我在vue js组件中上传了一个文件,该文件在服务器中发送了base64
methods: {
onFileChange(e) {
console.log(e.target.files[0]);
let fileReader = new FileReader();
fileReader.readAsDataURL(e.target.files[0]);
fileReader.onload = (e) => {
this.product.cover_image = e.target.result
};
},
<div class="form-group">
<label for="exampleInputFile">Upload Image of Product</label>
<input type="file" ref="fileupload" v-on:change="onFileChange" id="exampleInputFile">
</div>
并在我的laravel im控制器中使用图像干预通过Image::make
public function store(Request $request){
$this->validate($request, [
'name' => 'required|max:255',
'price' => 'required|numeric',
]);
$image = $request->get('cover_image');
$name = time().'.' . explode('/', explode(':', substr($image, 0, strpos($image, ';')))[1])[1];
Image::make($request->get('cover_image'))->save(public_path('cover_images/').$name);
$product = new Product;
$product->name = $request->input('name');
$product->description = $request->input('description');
$product->price = $request->input('price');
$product->cover_image = $name;
if($product->save()) {
return new ProductsResource($product);
}
}
在保存之前如何验证图像?它在base64中,我不知道如何在laravel上进行验证。
答案 0 :(得分:1)
我在AppServiceProvider
里面放了自定义验证
public function boot()
{
Validator::extend('image64', function ($attribute, $value, $parameters, $validator) {
$type = explode('/', explode(':', substr($value, 0, strpos($value, ';')))[1])[1];
if (in_array($type, $parameters)) {
return true;
}
return false;
});
Validator::replacer('image64', function($message, $attribute, $rule, $parameters) {
return str_replace(':values',join(",",$parameters),$message);
});
}
然后在validation.php
上放上
'image64' => 'The :attribute must be a file of type: :values.',
现在我可以用它来验证请求
'image' => 'required|image64:jpeg,jpg,png'
贷记https://medium.com/@jagadeshanh/image-upload-and-validation-using-laravel-and-vuejs-e71e0f094fbb
答案 1 :(得分:0)
如果您只想验证上传的文件为图像类型:
$this->validate($request, [
'name' => 'required|max:255',
'price' => 'required|numeric',
'cover_image' => 'required|image'
]);
正在验证的文件必须是图像(jpeg,png,bmp,gif或 svg)