I've created an endpoint that takes a CSV file, parses it (with the help of CsvHelper), does some conversions, and then persists that data to my SQL Server database. I'm able to pass a CSV file in just fine through the API, but I'm encountering an issue with getting this endpoint hooked up to my React front-end to where I can upload the CSV through the UI and call the endpoint to do the rest of the work. A 400: 'Object reference not set to an instance of an object' error is being thrown instead. I've looked through a ton of SO posts that had a similar issue to mine and have tried the solutions, but none of them have worked for my situation.
FileModel Class:
public class FileModel
{
public IFormFile FormFile { get; set; }
}
Upload Endpoint:
// I have these attributes here since the CSVs I will be uploading are pretty large.
[DisableRequestSizeLimit]
[RequestFormLimits(MultipartBodyLengthLimit = 234217728)]
[HttpPost("Upload")]
public async Task<ActionResult> CsvUpload([FromForm] FileModel file)
{
// Endpoint does the parsing and persisting here...
}
I don't believe the issue lies in what I'm doing within the endpoint so I left that out, but please let me know if it's needed.
React.js:
const reqHeaders = {
headers: {
'Accept': 'application/json, application/octet-stream, application/csv, text/plain, application/x-www-form-urlencoded, multipart/form-data, text/csv, */*',
},
}
let formData = new FormData()
formData.append('file', new Blob([fileSelector.current.files[0]]))
apiCalls.post("https://localhost:44323/api/MyController/Upload", formData, reqHeaders).then((res) => {
console.log(res)
setShowSnackbarSuccess(true)
setSnackbarMessage(`Successfully uploaded the data.`)
}).catch((e) => {
console.error(e)
setShowSnackbarError(true)
setSnackbarMessage('Failed to upload the data.')
}).finally(() => {
setShowBusyDialog(false)
setShowUploadProgressModal(false)
fileSelector.current.value = null
})
Does a file name need to be appended to the FormData object, or does something need to be added to the headers? I'm not quite sure at this point if this is an issue on the front-end of the back-end so any insight on why the error is being thrown is most appreciated. Also, the React code is not my code, but my partner's, so I'll try to answer the best I can on it.
Thanks in advance!
Does this method:
reside in a controller that inherits : ControllerBase ?
If so, perhaps you don't even need [FromForm] FileModel file
the following code should be able to handle uploaded text files: