Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

send form data with rtk query

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.

like image 202
Mehrad Farahnak Avatar asked Aug 31 '26 23:08

Mehrad Farahnak


1 Answers

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 👈
    };
  }
})
like image 103
bharatadk Avatar answered Sep 02 '26 13:09

bharatadk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!