I am trying to upload some files by sending it to an ASP.NET Core 6 Web API, but when I call the API, it throwing a 400 error. Please help me solve the issue.
File upload model:
public class FileUploadModel
{
public IFormFile[] Files { get; set; }
}
Web API action method:
[HttpPost("UploadFiles")]
public async Task<IActionResult> UploadFiles(FileUploadModel model)
{
if (model.Files == null || model.Files.Length == 0)
{
return BadRequest("No files selected");
}
foreach (var file in model.Files)
{
if (file == null || file.Length == 0)
{
// Skip optional files that were not uploaded
continue;
}
var uniqueFileName = $@"{Guid.NewGuid()}{file.FileName}";
var filePath = Path.Combine("/Uploads", uniqueFileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
// code to write file path to Database
return Ok("Files uploaded successfully");
}
}
API call using jQuery Ajax from frontend:
// Initialize a FormData object
var formData = new FormData();
// Add the files to the FormData object
formData.append("file1", $("#payslip")[0].files[0], "payslip");
formData.append("file2", $("#experience")[0].files[0], "experience");
formData.append("file3", $("#pg")[0].files[0], "pg");
formData.append("file4", $("#degree")[0].files[0], "degree");
formData.append("file5", $("#plustwo")[0].files[0], "plustwo");
formData.append("file6", $("#sslc")[0].files[0], "sslc");
// Make the Ajax call
$.ajax({
type: "POST",
url: "https://localhost:7049/api/SelectedCandidates/UploadFiles",
data: formData,
processData: false,
contentType: 'multipart/form-data',
xhrFields: {
withCredentials: true
},
success: function (result) {
alert("documents uploaded successfully");
},
error: function (xhr, status, error) {
alert("error "+status);
console.log(error);
}
});
When I try to call the API, I get a HTTP 400 Bad Request error and none of the code inside the UploadFiles
API method is working. I am new to .NET Core, please help me to figure out the issue.
Thanks in advance