Home > Mobile >  How to submit files to MVC Action using FormData
How to submit files to MVC Action using FormData

Time:03-15

I am creating an ASP.NET Core 6 file upload application. This is my code:

FORM

<form asp-controller="Home" asp-action="UploadFiles" method="post" enctype="multipart/form-data" id="uploadForm">
    <input type="file"  multiple name="files">
    @foreach (var folder in @Model.Folders)
    {
        <input id="filePathUrl" type="radio" asp-for="Folders" value="@folder" />
        @folder
    }
<button type="submit" >Upload Files</button>

jQuery

    function processFiles(confirmOverwrite = false){
    const filePath = $("#filePathUrl").val();
    const fileList = $(".form-control-file")[0].files;
    const files = Array.from(fileList);

    let formData = new FormData();
    files.forEach(file => formData.append("files[]", file));

    const URL = '@Url.Action("UploadFiles", "Home")';

    $.ajax({
        url: URL   '?folders='   filePath   '&confirmOverwrite='   confirmOverwrite,
        type: 'post',
        data: formData,
        // dataType: 'json',
        contentType: false,
        processData: false,
              ...

MVC Action

       [HttpPost]
    public async Task<JsonResult> UploadFiles(IEnumerable<IFormFile> files, string folders, bool confirmOverwrite = false)
    {
        List<string> existingFiles = new();
        var filesToBeSaved = new List<(IFormFile file, string filePath)>();
        
        foreach (var file in files)
        {
            string trimmedFileName = file.FileName.Replace(" ", "");
            var filePath = Path.Combine(folders, trimmedFileName);

            if (System.IO.File.Exists(filePath) && !confirmOverwrite)
            {
                existingFiles.Add(file.FileName   "("   trimmedFileName   ")");
            }
            else
            {
                filesToBeSaved.Add((file, filePath));
            }
        }
       ...

I have removed alot of code to keep things relevant and simple.

Why is files argument appearing as null when I submit the form??

CodePudding user response:

Model Binding binds the parameter by name. Your backend here IEnumerable<IFormFile> files name is files.

So you need change your code like below:

files.forEach(file => formData.append("files", file)); 

Besides, I know you may want to post it by array index. Only for complex list model type, you may need post like: model[index].PropertyName. Refer to here.

  • Related