Home > database >  How to send upload file to controller - files is always empty
How to send upload file to controller - files is always empty

Time:08-16

UserAdmin.cshtml

<div >
            <form id="upload-file-dialog-form" 
 novalidate 
onsubmit="UploadFile()" 
enctype="multipart/form-data"
method="post">
                 <div >
                    <p>Upload one or more files using this form:</p>
                        <input type="file" name="file_Uploader" />
                </div>

                <div >
                    <div >
                        <input type="submit"  value="Upload"/>
                        
                    </div>
                </div>        
            </form>
        </div>

UserAdmin.js

function UploadFile() {

var form = $('form')[0]; 
var formData = new FormData(form);
console.log(formData);

$.ajax({
    url: '/API/Upload',
    type: 'POST',
    data: formData,
    contentType: false, 
    processData: false,
    success: function (data) {
        
    },
    error: function () {
        
    }
});
}

Controller

[HttpPost]
    public async Task<IActionResult> Upload(List<IFileUpload> files)
    {
        try
        {
            var check = (HttpContext.Request.Form.Files);

            long size = files.Sum(f => f.Length);

            //some code removed
            return Ok(new { count = files.Count, size, filePaths });
        }
        catch (Exception exc)
        {
            logger.Error("Error in upload() "   exc.Message);
            throw;
        }
    }

the files in controller is always 0.

If onsubmit="UploadFile()" is replaced with

asp-controller="API" asp-action="Upload"

then I get something in check but again converting it to List of IFileUpload is another blocker

CodePudding user response:

First of all, If you want to upload multiple files you have to add multiple="multiple" in your input. FormData will be empty if you print it like this, you have to iterate through the items.

<input type="file" name="file_Uploader" multiple="multiple" />

Please follow the codes below, I tested it working.

Complete form

<form id="upload-file-dialog-form"
      onsubmit="UploadFile(event)">
    <div >
        <p>Upload one or more files using this form:</p>
        <input type="file" name="file_Uploader" multiple="multiple" />
    </div>

    <div >
        <div >
            <input type="submit"  value="Upload" />
        </div>
    </div>
</form>

Construct form data like below

<script>
    function UploadFile(e) {
        e.preventDefault();
        var formData = new FormData($('#upload-file-dialog-form')[0]);
        
        $.each($("input[type='file']")[0].files, function(i, file) {
            formData.append('files', file);
        });

        $.ajax({
            url: '/API/Upload',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            success: function(data) {

            },
            error: function() {

            }
        });
    }
</script>

Action method

[HttpPost]
        public async Task<IActionResult> Upload(List<IFormFile> files)
        {
            try
            {
                var check = (HttpContext.Request.Form.Files);

                long size = files.Sum(f => f.Length);

                return Ok(new { count = files.Count, size });
            }
            catch (Exception exc)
            {
                _logger.LogWarning("Error in upload() "   exc.Message);
                throw;
            }
        }

CodePudding user response:

In model class, use IFormFile

public List<IFormFile> file_Uploader {get;set;}"

In controller, change the parameter like this

public async Task<IActionResult> Upload(List<IFormFile> file_Uploader)

add multiple to upload more files, and keep the name attribute the same as parameter to post value, code like below:

 <input type="file" name="file_Uploader" multiple/>

result:

enter image description here

  • Related