File upload with Vue and Laravel

Asked By: Anonymous

I’m trying to make a simple User Avatar update using vue and laravel and I can’t figure what I’m doing wrong here.

I have a vue component with this form and this script:

<form @submit.prevent="updateAvatar" action="#" method="POST" enctype="multipart/form-data">
        <div class="form-group">
          <label name="task-title">Incarca poza:</label>
          <input @change="newAvatar" id="avatar" type="file" name="avatar">
        </div>
        <button type="submit" class="btn btn-primary general-task-btn">Actualizeaza</button>
      </form>

<script>
export default{
    props: ['userid'],
    data(){
        return{
            avatar: {
            }
        }
    },
    methods: {
    newAvatar(event) {
       let files = event.target.files;
       if (files.length) this.avatar = files[0];
    },
    updateAvatar: function () {
        let data = new FormData();
        data.append('file', this.avatar);
        axios.put('/api/user/updateAvatar', data)
                .then(res => {
                    console.log(res);
                 }) 
                 .catch(error => console.log(error));
        // window.location.href = "/profile";
      }
    }
}

Controller function:

    public function updateAvatar(Request $request)
{
    $user = Auth::user();
    $avatar = $request->file('file');
    $filename = time() . '.' . $avatar->getClientOriginalExtension();
    Image::make($avatar)->save( public_path('/uploads/avatars' . $filename) );

    $user->avatar = $filename;

    $user->save();
}

What I really don’t know is how to access that formData that I sent with axios. The server tells me that is empty.
I tried to console.log the formData before making the put request but I get an empty obj even if the content is in the avatar object. As I read online, you can’t see the content of a formData so I can’t figure if the data is being sent correctly or not.
Maybe you guys can make this clear for me.


Solution

Answered By: Anonymous

That seems to be related to this issue
https://github.com/laravel/framework/issues/13457

Try replacing

let data = new FormData(); 
data.append('file', this.avatar);
data.append('_method', 'put'); // add this
axios.post('/api/user/updateAvatar',data) // change this to post )
.then(res =>{
   console.log(res); 
}) 
.catch(error => console.log(error)); //             
   window.location.href = "/profile";
}

Windows 10 Kaufen Windows 10 Pro Office 2019 Kaufen Office 365 Lizenz Windows 10 Home Lizenz Office 2019 Home Business Kaufen Windows 10 Lisans Office 2019 Mac Satın Al follower kaufen instagram follower kaufen porno