I have to change the user's profile image, I am using Vuejs for this purpose, the problem is that it passes the image to me base64
and when I do decode in the method of myProfile
the controller it is simple or it saves the number 1 in the avatar field of the table user
or just pass it null
.
profile.vue
<template>
<input type="file" name="image" @change="getImage" accept="image/*">
<img :src="avatar" class="img-circle" width="150" />
<a href="" v-show="loaded" class="btn btn-success" @click.prevent="updateAvatar">Upload</a>
</template>
<script>
props: ['auth'],
data() {
return {
user: {},
errorss: {},
showMe: false,
loaded: false,
avatar: '',
}
},
mounted() {
this.user = JSON.parse(this.auth);
this.avatar = this.user.avatar;
},
getImage(e){
let image = e.target.files[0];
let reader = new FileReader();
reader.readAsDataURL(image);
reader.onload = e => {
this.avatar = e.target.result;
}
this.loaded = true;
},
updateAvatar(){
let urlAvatar = '/dashboard/avatar';
//let value = new FormData();
//value.append('image', this.avatar);
const value = {
'image': this.avatar
}
axios.put(urlAvatar, value)
.then((response) => {
let title = response.data.status;
let body = response.data.msg;
this.displayNotificationSuccess(title, body);
})
.catch((e) => {
console.log(e.response.data);
})
},
</script>
Note: When I occupy an FormData()
avatar it happens to me empty
myProfile
I have already made so many changes to the method that in the end I leave it like this to see how they can guide me.
myProfile (UserController)
public function myAvatar(Request $request)
{
$file_data = $request->image;
$avatar = Storage::putFile('public/defaults/users/avatar/', base64_decode($file_data));
$userAvatarUpdate = User::find(Auth::user()->id);
$userAvatarUpdate->avatar = $avatar;
$userAvatarUpdate->update();
return response()->json([
'status' => 'Muy bien!',
'msg' => 'Tu foto de perfil se actualizo.',
], 200);
}
I have seen several tutorials but I have not yet reached the solution that fits what I need.
Any ideas? I am using Laravel 5.6
, Vuejs 2
and Axios
.
To upload images with
axios
the by methodPUT
, you can "trick" and send bypost
fromvue
, but in Laravel access thePUT
. (there may be better ways to do it but it remains for investigation :) )The first recommendation for storing the images would be to continue using the
storage
but as I notice it tries to store directly in the project's public folder which is not entirely correct, but for the example we will continue with this configuration.config\filesystems.php
For this, in the default file thedriver
storage islocal
then you must change the value of theroot
storage folder for the local key usingpublic_path
that it will be equal to thepublic
project folder and within this we specify to Laravel that there will be a folderdefaults
In the controller it could just stay.
VueJs , (code explanation is included)
To publicly access the images you would have the path