Skip to content

Instantly share code, notes, and snippets.

@nadyshalaby
Last active August 23, 2017 22:34
Show Gist options
  • Save nadyshalaby/5a290d85f85dc67141ebe12361c20784 to your computer and use it in GitHub Desktop.
Save nadyshalaby/5a290d85f85dc67141ebe12361c20784 to your computer and use it in GitHub Desktop.
Uploading images through Laravel & VueJs, it's mush simpler and quicker than the normal way of handling the file uploads using vanilla js or jquery lib. also provide file preview.

Here's my code for uploading images through VueJs, it's mush simpler and quicker. also provide file preview.

VueJS Code


<template lang="html">
    <form @submit.prevent="submitAvatar">
        <img :src="image" alt="" />
        <input type="file" id="avatar" @change="updateAvatar" name="...">
        <a href="javascript:;" @click.prevent="removeImage"> Remove </a>
        <button type="submit" class="btn green"> Save Changes </button>
    </form>
 </template>

<script>

export default {
    props: ['upload-url', 'avatar'],
    data(){
        return {
        form: {
            avatar: '',
        },
        image: this.avatar? this.avatar : 'http://www.placehold.it/200x150/EFEFEF/AAAAAA&amp;text=no+image'
        }
    },
    methods: {
        updateAvatar(e){
            let files = e.target.files || e.dataTransfer.files;
            if (!files.length) {
                return;
            }
            this.form.avatar = files[0];
            this.previewImage(files[0]);
        },
        previewImage(file) {
            var reader = new FileReader();
            var vm = this;

            reader.onload = (e) => {
                vm.image = e.target.result;
            };

            reader.readAsDataURL(file);
        },
        removeImage: function (e) {
            this.image = 'http://www.placehold.it/200x150/EFEFEF/AAAAAA&amp;text=no+image';
            this.form.avatar = document.getElementById('avatar').value = '';
        },
        submitAvatar(e){
            this.$http.post(this.uploadUrl, form).then(function (data) {

            // TODO: display success alert

            }.bind(this));
        }
    }
}
</script>

Laravel Code


public function postAvatar(Request $request)
{
    $this->validate($request, [
        'avatar' => 'max:20000|mimes:jpg,jpeg,png,gif|image|file',
    ], [], [
        'avatar' => 'Avatar Image',
    ]);

    $user = auth()->user();

    if ($request->hasFile('avatar') && $request->avatar->isValid()) {
        $filename = microtime(time())."_".$request->avatar->getClientOriginalName();

        $request->avatar->move(public_path("imgs"), $filename);

        $user->avatar = $filename;

        $user->save();
    }

    return [
        'status' => 'success',
    ];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment