axios post file code example

Example 1: axios file upload

const formData = new FormData();
const imagefile = document.querySelector('#file');
formData.append("image", imagefile.files[0]);
axios.post('upload_file', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
})

Example 2: axios file upload

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'
    }
})

Example 3: upload file axios

uploadFile: function (event) {
    const file = event.target.files[0]
    axios.post('upload_file', file, {
        headers: {
          'Content-Type': file.type
        }
    })
}

Example 4: sending api request in axios with files

let headers = {
        Authorization: "token",
        'Content-Type':'multipart/form-data'
    };

let formData = new FormData();

 for(let key in files){
 
  formData.append('files[][file]', files[key].file, files[key].file.name)
  formData.append('files[][file_type_id]', files[key].fileType)
}

axios
    .post(
        "/api/files",
       formData,
        { headers }
    )
    .then(()=>{console.log('It Works')})

Tags:

Misc Example