I am trying to upload multiple files but using ajax , i am facing two specific problems
first(java script problem): how to loop through input files and put it inside array of files before sending (by ajax)
second:(c# problem): how to receive the files in backend (what type of data should i use as parameter data type?)
here is my failed attempt:
html code:
<input type="file" name="file" accept=".pdf,.docx,.doc" class="drop-zone__input" multiple>
jQuery:
<script>
$(document).ready(function () {
$('#addreply').click(
function () {
{
var files = $("#fileInput").get(0).files;
var fileData = new FormData();
for (var i = 0; i < files.length; i++) {
fileData.append("fileInput", files[i]);
}
var formData = new FormData();
//formData.append('file', $("[name='file']")[0].files[0]); // myFile is the input type="file" control
formData.append('reply', $("[name='reply']").val()); // myFile is the input type="file" control
formData.append('mid', @Model.Message.Id); // myFile is the input type="file" control
formData.append('files', fileData); // myFile is the input type="file" control
var _url = '@Url.Action("AddReplyDetails", "Messages")';
$.ajax({
url: _url,
type: 'POST',
data: formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function (result) {
//$('#file').val("")
$("#ssss").load(window.location + " #ssss").find('.rm').last().hide().fadeIn();
$('html, body').animate({
scrollTop: $('.rm').last().offset().top
}, 2500);
},
error: function (jqXHR) {
},
complete: function (jqXHR, status) {
}
});
}
$("#reply").val('')
});
});
</script>
backend:
public async Task<IActionResult> AddReplyDetails(List<IFormFile> files,IFormFile file, string reply, int mid)
{
string filesnames="";
foreach (var item in files)
{
filesnames +=await UserFile.UploadeNewFileAsync("", item, _environment.WebRootPath, Properties.Resources.Files);
filesnames += ",";
}
Message message = _context.Messages.SingleOrDefault(m => m.Id == mid);
message.LastActivitydate = DateTime.Now;
message.IsRead = false;
_context.Messages.Update(message);
_context.MessageReplies.Add(new MessageReply
{
ApplicationUserId = _userManager.GetUserId(User),
Content = reply.Replace("\n", "<br/>"),
Attachment = filesnames,
MessageId = mid,
DateOfRecord = DateTime.Now,
IsRead = false,
IsDeleted = false,
IsReported = false,
});
_context.SaveChanges();
return RedirectToAction("Details", "Messages", new { id = mid });
}