Skip to content

Instantly share code, notes, and snippets.

@cn-2k
Created November 17, 2021 12:13
Show Gist options
  • Save cn-2k/835651eb4ecd00f0e0aa3a14d01563d1 to your computer and use it in GitHub Desktop.
Save cn-2k/835651eb4ecd00f0e0aa3a14d01563d1 to your computer and use it in GitHub Desktop.
Upload image with Axios + Vue 3
<template>
<input type="file" @change="handleFileUpload($event)"/>
</template>
<script>
import axios from 'axios'
import { reactive, toRefs } from 'vue'
export default {
setup () {
const state = reactive ({
photo: null,
})
const handleFileUpload = (event) => {
state.photo = event.target.files[0];
}
let formData = new FormData();
formData.append('photo', state.photo)
axios
.post('URL', formData, {
headers: {
'Content-Type': 'multipart/form-data',
Authorization: 'Bearer ' + token,
},
})
return {
...toRefs(state),
handleFileUpload,
}
}
}
</script>
<style>
</style>
@cn-2k
Copy link
Author

cn-2k commented Nov 17, 2021

Note: only use headers if it's necessary for your request.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment