How to Set Multipart in Axios with React

How do I set multipart in axios with react?

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

Axios POST request sending nothing with 'multipart/form-data' [React Native - Expo]

So after diving through search results in Google, I've found this StackOverflow post: react native post form data with object and file in it using axios

I took the answer provided by user_2738046 in my code and it worked! Combining with Ali's suggestion here is the final code that worked.

const FormData = global.FormData;
const formData = new FormData();
formData.append("userId", user.userId);
formData.append("location", location);
formData.append("description", description);
images.forEach(img => {
const trimmedURI = (Platform.OS === "android") ? img.uri : img.uri.replace("file://", "");
const fileName = trimmedURI.split("/").pop();
const media = {
name: fileName,
height: img.height,
width: img.width,
type: mime.getType(trimmedURI),
uri: trimmedURI
};

formData.append("report-images", media);
});

const response = await axios({
method: "POST",
url: `http://${<my-ip-address>}:3003/api/report/submit`,
data: formData,
headers: {
'Content-Type': 'multipart/form-data'
},
transformRequest: (data, error) => {
return formData;
}
});

// If success, clear all text fields
if (response) {
showToast(7005);
setLocation("");
setImages([]);
setDescription("");
}

setShowLoading(false);

file upload using axios in react

To upload file with axios you need to use FormData:

const formData = new FormData();

// ...

formData.append("data", values.attachedFile[0]);
axios.post(app.resourceServerUrl + '/file/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})

axios post request to send form data

You can post axios data by using FormData() like:

var bodyFormData = new FormData();

And then add the fields to the form you want to send:

bodyFormData.append('userName', 'Fred');

If you are uploading images, you may want to use .append

bodyFormData.append('image', imageFile); 

And then you can use axios post method (You can amend it accordingly)

axios({
method: "post",
url: "myurl",
data: bodyFormData,
headers: { "Content-Type": "multipart/form-data" },
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});

Related GitHub issue:

Can't get a .post with 'Content-Type': 'multipart/form-data' to work @ axios/axios

Unable to send multipart form data to backend using axios from ReactJS

The solution was really really simple. I had difference in variable name(user) in the frontend FormData() and the backend multer code(user_name). This was causing the issue. By changing the variable name in multer to user, the request works fine.



Related Topics



Leave a reply



Submit