When I curl something, it works fine:
curl -L -i -H 'x-device-id: abc' -F "url=http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" http://example.com/upload
How do I get this to work right with axios? I'm using react if that matters:
uploadURL (url) { return axios.post({ url: 'http://example.com/upload', data: { url: url }, headers: { 'x-device-id': 'stuff', 'Content-Type': 'multipart/form-data' } }) .then((response) => response.data) }
This doesn't work for some reason.
To Use Axios POST Request to Send Form Data in ReactJS First Of all, make a variable named bodyFormData with FormData(). Then You can simply append your form data in bodyFormData just like this: bodyFormData. append('userName', 'milan'); and then you can simply use this bodyFormData in your axios post request data.
First, you create a local React state selectedFile using useState() hook to store the currently selected file, Second, the handleFileSelect event handler updates the selectedFile value using the setter function setSelectedFile and, Third, the handleSubmit function handles the post request to upload file using Axios.
Here's how I do file upload in react using axios
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() // Stop form submit 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
Source
If you are sending alphanumeric data try changing
'Content-Type': 'multipart/form-data'
to
'Content-Type': 'application/x-www-form-urlencoded'
If you are sending non-alphanumeric data try to remove 'Content-Type' at all.
If it still does not work, consider trying request-promise (at least to test whether it is really axios problem or not)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With