redux-api-middleware
redux-api-middleware copied to clipboard
how to send multipart/form-data
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
},
}
};`
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],
},
Leaving headers undefined works perfectly for us. Most browsers set the correct headers.
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],
},
};
}
I had to explicitly remove the Content-type
header, otherwise I got the error "Required request part 'file' is not present".
@burovmarley remove headers