axios multipart/form-data nodejs code example
Example 1: axios post formdata
axios({
method: 'post',
url: 'myurl',
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data' }
})
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
Example 2: axios multipart/form-data
import React from 'react'
import axios, { post } from 'axios';
class SimpleReactFileUpload extends React.Component {
constructor(props) {
super(props);
this.state ={
file:null
}
this.onFormSubmit = this.onFormSubmit.bind(this)
this.onChange = this.onChange.bind(this)
this.fileUpload = this.fileUpload.bind(this)
}
onFormSubmit(e){
e.preventDefault()
this.fileUpload(this.state.file).then((response)=>{
console.log(response.data);
})
}
onChange(e) {
this.setState({file:e.target.files[0]})
}
fileUpload(file){
const url = 'http://example.com/file-upload';
const formData = new FormData();
formData.append('file',file)
const config = {
headers: {
'content-type': 'multipart/form-data'
}
}
return post(url, formData,config)
}
render() {
return (
<form onSubmit={this.onFormSubmit}>
<h1>File Upload</h1>
<input type="file" onChange={this.onChange} />
<button type="submit">Upload</button>
</form>
)
}
}
export default SimpleReactFileUpload
Example 3: send multipart form data axios with node js
const axios = require('axios');
const FormData = require('form-data');
const form = new FormData();
form.append('field', 'a,b,c', 'blah.csv');
axios.post('http://example.org/endpoint', form, {
headers: form.getHeaders(),
}).then(result => {
console.log(result.data);
});