agraboso / redux-api-middleware

Redux middleware for calling an API.
MIT License
1.49k stars 202 forks source link

how to send multipart/form-data #125

Open burovmarley opened 7 years ago

burovmarley commented 7 years ago

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
    },
}

};`

coldfish commented 7 years ago

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],
    },
karladler commented 7 years ago

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

Keksike commented 6 years ago

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],
    },
  };
}
ludder commented 6 years ago

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

iamandrewluca commented 6 years ago

@burovmarley remove headers