So I am tinkering with an image uploader which will preview the image before uploading.
There are restrictions in place to allow just jpg, jpeg or png image formats, however, the error messages aren't being returned and I have tried a number of methods Please see my code below:
<template>
<div class="row">
<div class="col-md-12">
<img :src="image" class="img-responsive" alt="">
</div>
<div class="col-md-8">
<input type="file" v-on:change="onFileChange" class="form-control">
</div>
<div class="col-md-4">
<button class="btn btn-success btn-block" @click="upload">Upload</button>
</div>
</div>
</template>
This is being designed using Vue and Laravel. I am literally 1 day into learning Vue so please let me know if I have missed a vital part you need to look at (such as the route/controller)
<script>
export default {
data() {
return {
image: ''
}
},
methods: {
onFileChange(e) {
let files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.createImage(files[0]);
},
createImage(file) {
let reader = new FileReader();
let vm = this;
reader.onload = (e) => {
vm.image = e.target.result;
};
reader.readAsDataURL(file);
},
upload(){
axios.post('/api/upload',{image: this.image})
.then(response => {
});
}
}
}
</script>
Please see the controller below:
public function upload(Request $request)
{
$validator = Validator::make($request->all(), [
'image' => 'required|image64:jpeg,jpg,png'
]);
if ($validator->fails()) {
return response()->json(['errors'=>$validator->errors()]);
} else {
$imageData = $request->get('image');
$fileName = Carbon::now()->timestamp . '_' . uniqid() . '.' . explode('/', explode(':', substr($imageData, 0, strpos($imageData, ';')))[1])[1];
Image::make($request->get('image'))->save(public_path('images/').$fileName);
return response()->json(['error'=>false]);
}
}
'image64' => 'The :attribute must be a file of type: :values.',