简体   繁体   中英

Upload a file using vuejs and laravel without a form

I'm using vue.js 2.1 and Laravel 5.4 to upload a file from a component without a form.

Problem: On the server side, this statement return $request->file('my_file'); returns null. Why?

This is how the vue component looks like:

<template>
    <input id="my_file" type="file" @change="fileChanged($event)">
    <button v-if="my_file" @click="update">Upload</button>
</template>

<script>
export default {
    data () {
        return {
            my_file: null,
        }
    },

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

        createImage(file) {
            var image = new Image();
            var reader = new FileReader();
            var vm = this;

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

        update() {
            axios.put('/api/update/', {
                my_file: this.my_file,
            })
            .then(response => {
                console.log(response.data);
            })
            .catch(error => {
                console.log(error);
            });
        }
    }
}
</script>

On the server side, I have the following method:

public function update(Request $request)
{
    return $request->file('my_file');

    // $request->file('my_file')->store();
}

What am I missing? So I can use the function $request->file('my_file')->store(); provided by Laravel to upload the file.

EDIT I've changed the http verb from put to post like so:

trySomeThing () {
    var data = new FormData();
    var file = this.$refs.fileInput.files[0];
    data.append('attachment_file', file);
    data.append('msg', 'hello');

    axios.post('/api/try', data)
        .then(response => {
            console.log(response.data)
        });
},

On the controller, I have:

public function try(Request $request)
{
    if ($request->hasFile('my_file')) {
        $file = $request->file('my_file');
        //$file->getFilename();
        return var_dump($file);
    } else {
        return var_dump($_POST);
    }
}

The request header contains: 请求

The returned response shows this:

响应

First add a Vue reference to your file input.

<input id="my_file" type="file" @change="fileChanged($event)" ref="fileInput">

Then update your update method:

update() {
    var data = new FormData()
    var file = this.$refs.fileInput.files[0]
    data.append('my_file', file)
    axios.put('/api/update/', data)     
    .then(response => {
        console.log(response.data)
    })
    .catch(error => {
        console.log(error)
    });
}

In your laravel application:

if ($request->hasFile('my_file')) {
   $file = $request->file('my_file');
   dd($file);
}

For more info: Laravel documentation

Your view should look something like this

<template>
<div class="row">
    <div class="col-md-12">
        <div class="col-md-2">
            <img :src="image" class="img-responsive">
        </div>
        <div class="col-md-8">
            <input type="file" v-on:change="onFileChange" class="form-control">
        </div>
        <div class="col-md-2">
            <button class="btn btn-success btn-block" @click="upload">Upload</button>
        </div>
       </div>
   </div>
</template>
<style scoped>
img{
    max-height: 36px;
}
</style>
<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM