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 returned response shows this:


formDatain vuejs