2

I am uploading a file in the body as form-data. Using ajax it works fine but when I try to do the same in redux-saga, it does not work and fails. What am I doing wrong?

In ajax,

let upload = ajax.post(PathHelper.apiPath + '/create/text').field('file', file);
    upload.end((err, response) => {
      if (err) {
        console.log('Error Encountered', err);
      }
      if (response) {
        const imageResponse = response.body;
        console.log('imageresponse: ', imageResponse);
      }
    });

Here is my saga code:

export function* fetchText(text) {
const formData = new FormData();
  formData.append('file', text.data);
  console.log('formData: ', formData);
  try {
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: formData
    };
    const response = yield call(fetchJson, PathHelper.apiPath + '/create/text', options);
    console.log('response: ', response);

  } catch (err) {
    console.log('Error saving your image', err);
  }
 }
fscore
  • 2,567
  • 7
  • 40
  • 74

1 Answers1

0

when I try to do the same in redux-saga, it does not work and fails

Redux-saga itself is about perform asynchronous action, fired on some redux event, so firstly, maybe put action is omitted - usually saga intercepts request-like action and creates success action after operation is completed. In that case, there should be redux-reducer, which will accept API call result and apply it somethere on UI component.

Secondly, uploading files requires live HTML form with enctype="multipart/form-data", and FormData object should be attached to original form. See details here: http://researchhubs.com/post/computing/javascript/upload-files-with-ajax.html

Vladislav Ihost
  • 2,127
  • 11
  • 26