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