Not able to upload files to server in ASP.NET MVC - always get a count of 0

Viewed 77

I am trying to upload files to a server with ASP.NET MVC. I am using Ajax and a controller, my code seems working but it's not able to upload the files to the server.

Here is my code; can you please tell me what I am doing wrong?

function SubmitAddEdit(form) {
    $.validator.unobtrusive.parse(form);
    if ($(form).valid()) {
        var data = $(form).serializeJSON();
        data = JSON.stringify(data);
        $.ajax({
            type: 'POST',
            url: apiurl,
            data: data,
            contentType: 'application/json',
            success: function (data) {
                if (data.success) {
                    popup.modal('hide');
                    ShowMessage(data.message);
                    dataTable.ajax.reload();
                } else {
                    ShowMessageError(data.message);
                }
            }
        });

    }
    return false;
}
<form onsubmit="return SubmitAddEdit(this)" enctype = "multipart/form-data">

        <div class="col-lg-6">
            
                <!-- The file input field used as target for the file upload widget -->
                <input type="file" name="files" id="files" multiple="multiple">
        </div>
</form>

public async Task<IActionResult> PostTicket(List<IFormFile> files, [FromBody] Ticket ticket)
{
    var fileName = await _dotnetdesk.Ticket(files, _env);
}

public async Task<string> Ticket(List<IFormFile> files, IHostingEnvironment env)
{
    var result = "";

    var webRoot = env.WebRootPath;
    var uploads = System.IO.Path.Combine(webRoot, "uploads");
    var extension = "";
    var filePath = "";
    var fileName = "";

    foreach (var formFile in files)
    {
        if (formFile.Length > 0)
        {
            extension = System.IO.Path.GetExtension(formFile.FileName);
            fileName = Guid.NewGuid().ToString() + extension;
            filePath = System.IO.Path.Combine(uploads, fileName);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await formFile.CopyToAsync(stream);
            }

            result = fileName;
        }
    }

    return result;
}

This is my code for the uploading the file through ASP.NET MVC, but it is not going inside the loop and every time I will get count of 0 for the file when I try to debug it. Please let me know what I am doing wrong.

1 Answers

One problem is with these lines:

var data = $(form).serializeJSON();
data = JSON.stringify(data);

You do not want a string representation of your files that would be a very inefficient way of doing things and I don't think this method of getting it would work anyway.

Instead of stringifying the form, pass it in directly as the data or build a new FormData object like this:

var data = new FormData();
data.append('files', form.files.files)

and use that as the data for the Ajax request.

Related