I'm using Axios on the client side to send HTTP requests to a remote Node.js server. How might I go about sending files in the request body using Axios? I also have to send other information in the request body - sending just the files to the server will not suffice. How might I go about doing this? I am open to using a different HTTP client as well.
1 Answer
Use a FormData instance. On node you can use the form-data npm package. Then you just send that FormData instance as the data in an axios request.
var formData = new FormData();
formData.append("username", "Groucho");
formData.append("accountnum", 123456); // number 123456 is immediately converted to a string "123456"
// HTML file input, chosen by user
formData.append("userfile", fileInputElement.files[0]);
// JavaScript file-like object
var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
var blob = new Blob([content], { type: "text/xml"});
formData.append("webmasterfile", blob);
axios.post("http://foo.com/submitform.php", formData);