How to post a file from a form with Axios

JavascriptAjaxFile UploadAxios

Javascript Problem Overview


Using raw HTML when I post a file to a flask server using the following I can access files from the flask request global:

<form id="uploadForm" action='upload_file' role="form" method="post" enctype=multipart/form-data>
    <input type="file" id="file" name="file">
    <input type=submit value=Upload>
</form>

In flask:

def post(self):
    if 'file' in request.files:
        ....

When I try to do the same with Axios the flask request global is empty:

<form id="uploadForm" enctype="multipart/form-data" v-on:change="uploadFile">
<input type="file" id="file" name="file">
</form>

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

If I use the same uploadFile function above but remove the headers json from the axios.post method I get in the form key of my flask request object a csv list of string values (file is a .csv).

How can I get a file object sent via axios?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

https://codepen.io/pmarimuthu/pen/MqqaOE

Solution 3 - Javascript

If you don't want to use a FormData object (e.g. your API takes specific content-type signatures and multipart/formdata isn't one of them) then you can do this instead:

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

Solution 4 - Javascript

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

Solution 5 - Javascript

Sharing my experience with React & HTML input

Define input field

<input type="file" onChange={onChange} accept ="image/*"/>

Define onChange listener

const onChange = (e) => {
  let url = "https://<server-url>/api/upload";
  let file = e.target.files[0];
  uploadFile(url, file);
};

const uploadFile = (url, file) => {
  let formData = new FormData();
  formData.append("file", file);
  axios.post(url, formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    }).then((response) => {
      fnSuccess(response);
    }).catch((error) => {
      fnFail(error);
    });
};
const fnSuccess = (response) => {
  //Add success handling
};

const fnFail = (error) => {
  //Add failed handling
};

Solution 6 - Javascript

How to post file using an object in memory (like a JSON object):

import axios from 'axios';
import * as FormData  from 'form-data'

async function sendData(jsonData){
    // const payload = JSON.stringify({ hello: 'world'});
    const payload = JSON.stringify(jsonData);
    const bufferObject = Buffer.from(payload, 'utf-8');
    const file = new FormData();

    file.append('upload_file', bufferObject, "b.json");

    const response = await axios.post(
        lovelyURL,
        file,
        headers: file.getHeaders()
    ).toPromise();


    console.log(response?.data);
}

Solution 7 - Javascript

For me the error was the actual parameter name in my controller... Took me a while to figure out, perhaps it will help someone. Im using Next.js / .Net 6

Client:

export const test = async (event: any) => {
    const token = useAuthStore.getState().token;
    console.log(event + 'the event')
    if (token) {
        const formData = new FormData();
        formData.append("img", event);
        const res = await axios.post(baseUrl + '/products/uploadproductimage', formData, {
            headers: {
                'Authorization': `bearer ${token}`
            }
        })
        return res
    }
    return null
}

Server:

 [HttpPost("uploadproductimage")]
        public async Task<ActionResult> UploadProductImage([FromForm] IFormFile image)
        {
            return Ok();
        }

Error here because server is expecting param "image" and not "img:

formData.append("img", event);

 public async Task<ActionResult> UploadProductImage([FromForm] IFormFile image)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDon SmytheView Question on Stackoverflow
Solution 1 - JavascriptNiklesh RautView Answer on Stackoverflow
Solution 2 - JavascriptmarisView Answer on Stackoverflow
Solution 3 - JavascriptNathan BlakeView Answer on Stackoverflow
Solution 4 - JavascriptOCornejoView Answer on Stackoverflow
Solution 5 - JavascriptJafar KaruthedathView Answer on Stackoverflow
Solution 6 - JavascriptYarhView Answer on Stackoverflow
Solution 7 - JavascriptIAmdeGrootView Answer on Stackoverflow