0

I have a input field as :

<input
          type="file"
          className="custom-file-selector-input"
          data-qa="custom-file-selector-input"
          accept="text/csv"
          onChange={this.handleFileInputSelectorChange}
          ref={element => (this.fileSelectorRef = element)}
        />

My handleFileInputSelectorChange function looks like this :

handleFileInputSelectorChange(event) {
let selectedCsvFile = event.currentTarget.files[0];
let fileReader = new FileReader();

fileReader.onload = e => {
  this.setState({
    fileResult: fileReader.result,
    uploadFile: true,
    **selectedCsvFile: selectedCsvFile**,
    selectedCsvFileName: selectedCsvFile.name
  });
};
fileReader.readAsText(selectedCsvFile);
}

I am having an upload button where I am calling a service which POSTs my request to a server:

const file = this.state.selectedCsvFile;
**let formData = new FormData();
formData.append("file", file);**
uploadCsv(someUrl, formData)
  .then(response => {
    return response.json();
  })
  .then(data => {
    console.log("data", data);
  })
  .catch(error => {
    console.log("error", error);
  });

I am not sure if the way I am appending the file to the FormData is correct or not. I am receiving error code 500 as in response.

My function that posts request is as below.

export const uploadCsv = (url, formData) => {
let authHeader = new Headers({
"Authorization": `Bearer MY-CUSTOM-AUTH-TOKEN`
});

return fetch(url, {
method: "POST",
body: formData,
headers: authHeader 
}).then(res => {
if (res.ok) {
  return res.json();
} else {
  if (res.status === 401) 
    return renewAuthToken(authPost, url, formData);
 else 
   return handleErrorResponse(res);
}
});
};

Can anyone help me with where I am going wrong. I am a little new to ReactJs and overall UX programming. Not sure if this is the way of posting a file in POST method

Einstein_AB
  • 396
  • 5
  • 22
  • Maybe you should pass `formData` to `uploadCsv`, and not `file` …? – 04FS Apr 11 '19 at 13:39
  • That was the typo, a residual code where I was trying to send file directly to my uploadCsv() function rather than wrapping it inside FormBody. I corrected the question. – Einstein_AB Apr 11 '19 at 13:42
  • Check if answers to these questions help you. 1. https://stackoverflow.com/questions/45477687/post-a-file-with-react-js and 2. https://stackoverflow.com/questions/39695275/react-js-handling-file-upload – Nik Apr 11 '19 at 13:45
  • Also what content-type does your file upload API expects? And what error message is shown under networks tab in developer console? – Nik Apr 11 '19 at 13:47
  • 1
    @Nik my content type shows 'Content-Type: multipart/form-data' in Response Headers. My API expects the same. – Einstein_AB Apr 11 '19 at 14:04
  • I noticed that my Request Headers : 'Content-Type: multipart/form-data' and my Request Headers in Form Data shows : Content-Type: application/vnd.ms-excel. Does this affects anything? – Einstein_AB Apr 11 '19 at 14:51

0 Answers0