qasimbotani's avatar

VueJS2 Proper file Upload request

Hello,

I think not only me alot of beginners are having the issue of uploading files. If someone with knowledge could post a proper working code for this. I have googled a lot for the whole day. The codes I get either work with VueJS1 or not working. If someone would help us the beginners in this regard I will be glad and the community will be richer :)

Thanks

0 likes
2 replies
mazedlx's avatar

I hope this will help:

<template>
<div>
    <div class="form-group">
        <label class="col-md-3 control-label">Picture</label>
        <div class="col-md-6">
            <input type="file" class="form-control" @change="fileSelected">
            <div v-if="image">
                <img :src="image" width="300px" class="img">
                <button type="button" class="btn btn-danger"     @click="removeImage"><i class="fa fa-fw fa-trash"></i></button>
            </div>
        </div>
    </div>
</div>
</template>
<script>
    export default {
        data() {
            return {
                image: '',
            };
        },

        methods: {
            fileSelected: function(e) {
                let files = e.target.files || e.dataTransfer.files;
                if (!files.length) {
                     return;
                }
                this.createImage(files[0]);
            },

            createImage(file) {
                let image = new Image();
                let reader = new FileReader();

                reader.onload = (e) => {
                    this.image = e.target.result;
                };
                reader.readAsDataURL(file);
            },

            removeImage: function (e) {
                this.image = '';
            },
        },
    }
</script>`

this.image is the file base64 encoded. This can be either saved to the database or to a real file with PHP.

2 likes
qasimbotani's avatar

Thanks for the reply, at the moment Im doing this through javascript using the following code:

var frm = new FormData();

and Im sending the form content but when I use FormData I face issues like input field with date type.

and on laravel 5.3 controller I want to use

$request->hasFile('file');

and then I want to be able to use storage to store the files I get from form. Can I use store to save the retrieved base64 encoded file to storage?

lets say something as follows? if yes how?

$request->file->store('/images/files/');

Thanks again

Please or to participate in this conversation.