How to pass formData and body parameters in axios post request - javascript

i want to pass formdata and data in body parameter in axios post request, i tried some way but its not working.
//code
const form = new FormData();
form.append("file", this.state.selectedFile);
const data={
token:localStorage.getItem('token'),
}
axios.post('http://localhost:3000/api/upload',form, {
onUploadProgress: ProgressEvent => {
this.setState({
loaded: (ProgressEvent.loaded / ProgressEvent.total*100),
})
},
})
.then(response=>{
console.log(response)
}).then(res => {
toast.success('upload success')
})
.catch(err => {
toast.error('upload fail')
})

You need to provide valid headers for respective content type
axios({
method: 'post',
url: 'http://localhost:3000/api/upload',
data: form,
headers: {'Content-Type': 'multipart/form-data' }
})

You are trying to pass a file in FormData which is not possible and you need to use FormUrlEncoded. To do so you also need to install a npm package named query-string and then your data property would look something like this:
import qs from 'query-string';
...
axios.post(..., data:qs.stringify({
file: this.state.selectedFile
})

Related

Not able to send files data from front-end (react.js) to back-end (node)

I have an application that stores to its state files' content, whether images, audio or both, as shown here with the mediaAudio object key:
In my react.js code, I make my post as such:
var bodyFormData = new FormData();
bodyFormData.append('data', formData);
axios({
method: "post",
url: 'http://localhost:5000/post-entry',
data: bodyFormData,
headers: { "Content-Type": "multipart/form-data" },
})
.then((response) => {
console.log(response);
})
.catch((response) => {
console.log(response);
});
In my node.js code, I retrieve my data as such:
app.post('/post-entry', (req, res) => {
let data = req.body.data;
console.log(data);
});
However, I'm not able to get the data being logged, it returns undefined.
What is happening?
Thanks

read file with php that sent by axios with content-type : image/jpeg [duplicate]

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?
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'
}
})
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
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
}
})
}
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
};
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});
});
this is my way:
var formData = new FormData(formElement);
// formData.append("image", imgFile.files[0]);
const res = await axios.post(
"link-handle",
formData,
{
headers: {
"Content-Type": "multipart/form-data",
},
}
);
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);
}
There is an issue with Axios version 0.25.0 > to 0.27.2 where FormData object in a PUT request is not handled correctly if you have appended more than one field but is fine with one field containing a file, POST works fine.
Also Axios 0.25.0+ automatically sets the correct headers so there is no need to specify Content-Type.
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)

axios doesn't get post request in redux-form

I have this code:
import axios from 'axios'
const storeDevices = values => {
axios.create({
baseURL: 'http://localhost:8000/something/store',
method: 'POST',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: values
});
}
export default storeDevices;
The following code is correct because it returns an object with all data from my form
const storeDevices = values => {
console.log(values);
}
export default storeDevices;
Interestingly if I try to use .then I have an error:
axios__WEBPACK_IMPORTED_MODULE_0___default.a.create(...).then is not a
function
Code with .then
axios.create({
baseURL: 'http://localhost:8000/something/store',
method: 'POST',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: values
}).then(res => {
console.log(res);
console.log(res.data);
});
It's because you've never told axios to send a POST request. axios.create creates a new instance of axios with a custom config. This instance have different methods (like .get(), .post(), etc.), none of which is then(), so that's why you received the error .then is not a function. You set the default method to POST but you've never sent a request.
I think you wanted to create this new instance because you didn't want to add the base URL and headers every single time. If you want to create a base instance, you can assign the returned value to a new variable:
const API = axios.create({
baseURL: 'http://localhost:8000/api/',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
});
And use this instance to post your request:
API.post('store', data)
.then(res => {
console.log(res);
console.log(res.data);
});
can you try to post using this sintax?
axios.post('http://localhost:8000/something/store', values, {headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},}
}).then(res => {
console.log(res);
console.log(res.data);
});

Axios request not receiving formData with content-type set

I have the following data being added to my formData()
let uploadData = new FormData();
uploadData.append("peer-video", this.state.peerVideo);
uploadData.append("peer-video-thumbnail", this.state.peerVideoThumbnail);
uploadData.append("project-video", this.state.projectVideo);
uploadData.append(
"project-video-thumbnail",
this.state.projectVideoThumbnail
);
this.state.documents.forEach(item => {
uploadData.append("documents", item);
});
The uploadData has key value pairs in it, I did formData.entries() to check this. And my axios request is as follows:
export const addProject = data => dispatch => {
axios
.post("/api/portfolio/add-project", data, {
headers: {
"Content-Type": `multipart/form-data`
}
})
.then(res => {
dispatch({
type: ADD_PROJECT,
payload: res.data
});
})
.catch(err => {
dispatch({
type: ADD_PROJECT,
payload: err
});
});
};
And if I go to my payload in the network tab I see this:
{"uploadData":{}}
Any suggestions? Thank you for taking the time to help me.
Edit
I tried the following structure in my axios request and it yielded the same result.
axios({
method: "post",
url: "/api/portfolio/add-project",
data: data,
config: { headers: { "Content-Type": "multipart/form-data" } }
})
When I execute the following
for (let keys of uploadData.entries()) {
console.log(keys);
}
These are the values:
I also noticed on formData docs that
Note: If you specify a Blob as the data to append to the FormData object, the filename that will be reported to the server in the "Content-Disposition" header used to vary from browser to browser.
But i'm not sure if that's what is causing my issue here?
Welp, this is what happens when your eyes stare at a screen too long.
this.props.addProject({
title: this.state.title,
company: this.state.company,
description: this.state.description,
role: this.state.role,
skills: this.state.skills,
uploadData: uploadData
});
Needed to simply be:
this.props.addProject(uploadData)
Thank you #vortex
Looks like you are posting an undefined variable called data rather than your uploadData

axios - send form data AND non-form data

I'm using axios to send data to my nodejs/express server. If I want to send form data, I do the following (and it works fine):
const formData = new FormData();
formData.append('nameOfFile', the_file);
axios({
method: 'post',
url: '/someRoute',
data: formData
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
// Do something with response
}).catch(err => {
// Do something with err
});
Again, the above code works fine. Here is the /someRoute endpoint that it goes to:
app.post('/someRoute', (req, res) => {
const uploadedFile = req.files.nameOfFile;
res.send('success'):
});
The endpoint always successfully receives the file. So far, so good.
If I want to send some other piece of data, like a date, I can send it like so (and it also works):
const date = '2012-02-13';
axios({
method: 'post',
url: '/someRoute',
data: date
})
app.post('/someRoute', (req, res) => {
const date = req.body.date;
res.send('success'):
});
But how do I send both the formDate and date data? I tried the following (but it doesn't work):
const formData = new FormData();
formData.append('nameOfFile', the_file);
axios({
method: 'post',
url: '/someRoute',
data: {
form: formData,
date: '2012-02-13'
},
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
// Do something with response
}).catch(err => {
// Do something with err
});
And the endpoint:
app.post('/someRoute', (req, res) => {
const uploadedFile = req.files.nameOfFile;
const date = req.body.date;
res.send('success'):
});
This gives me a 500 ERROR.
You can do the same thing you already did, just append the other data you also want to send to formData..
So
formData.append(‘date’, date);

Categories