How to post a file from a form with Axios
Add the file to a formData
object, and set the Content-Type
header to multipart/form-data
.
var formData = new FormData();var imagefile = document.querySelector('#file');formData.append("image", imagefile.files[0]);axios.post('upload_file', formData, { headers: { 'Content-Type': 'multipart/form-data' }})
Sample application using Vue. Requires a backend server running on localhost to process the request:
var app = new Vue({ el: "#app", data: { file: '' }, methods: { submitFile() { let formData = new FormData(); formData.append('file', this.file); console.log('>> formData >> ', formData); // You should have a server side REST API axios.post('http://localhost:8080/restapi/fileupload', formData, { headers: { 'Content-Type': 'multipart/form-data' } } ).then(function () { console.log('SUCCESS!!'); }) .catch(function () { console.log('FAILURE!!'); }); }, handleFileUpload() { this.file = this.$refs.file.files[0]; console.log('>>>> 1st element in files array >>>> ', this.file); } }});
This works for me, I hope helps to someone.
var frm = $('#frm');let formData = new FormData(frm[0]);axios.post('your-url', formData) .then(res => { console.log({res}); }).catch(err => { console.error({err}); });