Reputation: 1272
I wanna send an image with form data to the nest js server with RTK query but the file didn't send. the code are:
uploadImage: builder.mutation<any, any>({
query: (imageFile) => {
var bodyFormData = new FormData();
bodyFormData.append('file', imageFile);
console.log({ bodyFormData, imageFile });
return {
url: '/uploader/image',
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data;'
},
body: { bodyFormData }
};
}
})
I can send an image with Axios but in RTK I cant.
Upvotes: 7
Views: 15751
Reputation: 415
I am using rtk v2.2.5 and it works by changing "body" to "data"
query: (data) => {
const formData = new FormData();
formData.append('file', data.file);
return ({
url: `url here`,
method: 'POST',
data: formData, // previously it was -> body: formData
})
},
Upvotes: 0
Reputation: 11
Adding header 'Skip-Content-Type': true, helped in my case
Example:
uploadImage: builder.mutation<any, any>({
query: (imageFile) => {
var bodyFormData = new FormData();
bodyFormData.append('file', imageFile);
console.log({ bodyFormData, imageFile });
return {
url: '/uploader/image',
headers: {
'Skip-Content-Type': true
},
method: 'POST',
body: bodyFormData
};
}
})
Upvotes: 0
Reputation: 170
Just sending the FormData directly on the body
works for me. No need to manually set the header (it will be set for you) nor adding formData: true
.
Example:
uploadImage: builder.mutation<any, any>({
query: (imageFile) => {
var bodyFormData = new FormData();
bodyFormData.append('file', imageFile);
console.log({ bodyFormData, imageFile });
return {
url: '/uploader/image',
method: 'POST',
body: bodyFormData
};
}
})
Upvotes: 3
Reputation: 1
In my case, adding "Accept", "application/json"
in addition to formData: true
solved the problem.
Upvotes: -3
Reputation: 482
Remove body: { bodyFormData }
instead use body: bodyFormData
.
Additionally, you could try using this structure:
var bodyFormData = new FormData();
bodyFormData.append('file', {
uri: imageFileUri,
type: "image/jpeg",
name: imageFileUri?.split('/')[imageFileUri?.split('/').length - 1]
});
Upvotes: 2
Reputation: 639
You should also pass another parameter called formData in RTK Query while passing formdata in API request.
uploadImage: builder.mutation<any, any>({
query: (imageFile) => {
var bodyFormData = new FormData();
bodyFormData.append('file', imageFile);
console.log({ bodyFormData, imageFile });
return {
url: '/uploader/image',
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data;'
},
body: { bodyFormData },
formData:true //add this line 👈
};
}
})
Upvotes: 8