I'm working on a .Net 8 API and I need to pass form data which consists of files and other form elements to the controller via ajax.
I'm being able to pass a single file successfully, but the weird thing is that cannot pass an array of files.
(I shortened the code for simplicity)
JavaScript:
let arrayFiles = [];
arrayFiles.push(fileSelector.files[0]);
formData.append('files', arrayFiles[0]);
formData.append('test', test);
formData.append('saveMode', saveMode);
formData.append('deletedElements', deletedElements);
$.ajax({
url: '/Test/SaveTest',
method: 'POST',
contentType: false,
processData: false,
data: formData,
success: function (res) {
},
error: function () {
}
})
Controller:
public async Task<JsonResult> SaveTest(string test, int saveMode, IFormFile files, string deletedElements = "")
{
var deletedQuestions = deletedElements.DeserializeNodeToList<QuestionDTO>("DeletedQuestions");
var deletedAnswers = deletedElements.DeserializeNodeToList<AnswerDTO>("DeletedAnswers");
var testDto = test.DeserializeTest(deletedQuestions, deletedAnswers);
if (testDto == null) return Json(new { Success = false });
var saveResult = await _service.CreateTestAsync(testDto, saveMode);
return Json(saveResult);
}
This way I'm receiving one IFormFile object from form with no problems, but the fact is I need to pass multiple files.
I tried:
formData.append('files', arrayFiles); //removed the index to pass the whole array
plus:
public async Task<JsonResult> SaveTest(string test, int saveMode, IFormFile[] files, string deletedElements = "")
or
public async Task<JsonResult> SaveTest(string test, int saveMode, List<IFormFile> files, string deletedElements = "")
to no avail.
I shortened the code for simplicity, but actually what I really need to do is to pass an array of type:
[string, file]
to controller, where the "string" will contain a customized name of the file and "file" the file object itself.
Ok, I found the answer myself thanks to:
Send array of files from Jquery ajax to controller action
The key is the next:
Instead of doing one FormData.append with the whole array you have to do as many appends as images you need to pass keeping the same key, so instead of (for example):
let arrayFiles = [];
arrayFiles.push(fileSelector.files[0]);
arrayFiles.push(fileSelector.files[1]);
formData.append('files', arrayFiles);
You will do:
let arrayFiles = [];
arrayFiles.push(fileSelector.files[0]);
arrayFiles.push(fileSelector.files[1]);
formData.append('files', arrayFiles[0]);
formData.append('files', arrayFiles[1]);