redux-api-middleware icon indicating copy to clipboard operation
redux-api-middleware copied to clipboard

how to send multipart/form-data

Open burovmarley opened this issue 7 years ago • 5 comments

I'm trying to send file selected by the react-dropzone but I couldn't accomplish this. In some cases call_api is doing nothing no request / no error and in some cases request is sent but without mutlipart info and my server throws exception the request was rejected because no multipart boundary was found]

the code which I think is correct with your documentation is bellow ` let test = (files) => {

let formData = new FormData();
formData.append('file', files[0]);

return {
    [CALL_API]: {
        types: [UPLOAD_BEGIN, UPLOAD_SUCCESS, UPLOAD_FAILURE],
        endpoint: '/report/RIF/definition',
        method: 'post',
        headers: {'Content-Type': 'multipart/form-data'},
        body: formData
    },
}

};`

burovmarley avatar Apr 14 '17 06:04 burovmarley

I may suggest you to add boundary to CALL_API.headers like this:

    [CALL_API]: {
      endpoint: `${ROOT_URL}/upload`,
      method: 'POST',
      headers: {
        'Content-type': 'multipart/form-data, boundary=--abc--abc--'
      },
      body: data,
      types: [UPLOAD_BEGIN, UPLOAD_SUCCESS, UPLOAD_FAILURE],
    },

coldfish avatar May 16 '17 14:05 coldfish

Leaving headers undefined works perfectly for us. Most browsers set the correct headers.

karladler avatar Jun 09 '17 11:06 karladler

Can confirm: as long as body is a FormData-object, it should work without headers!

Example where I send a File file along with a string parameter called description:

import { RSAA } from 'redux-api-middleware';

export function uploadFile(file, description) {
  const data = new FormData();
  data.append('file', file);
  data.append('description', description || '');

  return {
    [RSAA]: {
      endpoint: '/uploadFile',
      method: 'POST',
      body: data,
      types: [FILE_UPLOAD_START, FILE_UPLOAD_SUCCESS, FILE_UPLOAD_FAILURE],
    },
  };
}

Same example with Flow-types for clarity:

import { RSAA } from 'redux-api-middleware';

export function uploadFile(file: File, description: string): { [typeof RSAA]: ApiCallAction } {
  const data = new FormData();
  data.append('file', file);
  data.append('description', description || '');

  return {
    [RSAA]: {
      endpoint: '/uploadFile',
      method: 'POST',
      body: data,
      types: [FILE_UPLOAD_START, FILE_UPLOAD_SUCCESS, FILE_UPLOAD_FAILURE],
    },
  };
}

Keksike avatar Oct 09 '17 10:10 Keksike

I had to explicitly remove the Content-type header, otherwise I got the error "Required request part 'file' is not present".

ludder avatar Oct 20 '17 11:10 ludder

@burovmarley remove headers

iamandrewluca avatar Feb 13 '18 19:02 iamandrewluca