djack109
djack109

Reputation: 1377

How do I upload a file using Bootstrap4 custom file upload via ajax

I'm struggling to get a file to upload. I've checked a dozen samples here (copied code verbatim) and nothing works. I get no errors, no upload, I just get nothing.

I set a breakpoint in my controller but it doesn't get hit. All my code is below, what am I doing wrong

I'm using asp.net.core 2.2 and VS2019

HTML

<div class="card">
    <div class="card-header">
        <div class="row">
            <div class="col">
                <h4>Import Users</h4>
            </div>
            <div class="col">
                <form id="frmUpload" action="@Url.Action("PerformImportUsers","Admin")" method="post">
                    @Html.AntiForgeryToken()
                    <div class="input-group">
                        <div class="custom-file">
                            <input type="file" class="custom-file-input" name="importFile" id="inputGroupFile02">
                            <label class="custom-file-label" for="inputGroupFile02" style="overflow:hidden;">Choose file</label>
                        </div>
                        <div class="input-group-append">
                            <a href="" class="input-group-text btn btn-primary" id="uploadFile"><span class="fa fa-upload"></span></a>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

JS

<script>
    $("#uploadFile").on("click", function (e) {
        e.preventDefault();
        //e.stopPropagation();

        debugger;
        var myForm = $("#frmUpload");
        var sUrl = myForm.attr("action");

        var files = $("#inputGroupFile02").get(0);
        var formData = new FormData();

        for (var i = 0; i != files.length; i++) {
            formData.append("myfile", files[i]);
        }

        $.ajax({
            type: "POST",
            url: sUrl,            
            contentType: false,
            processData: false,
            data: formData,
            success: function (result) {    
                var data = jQuery.parseJSON(result);
                showNotify(data.message);
            },
            error: function () {
                alert("there was an error");
            }
        });
    });
</script>

CONTROLLER

    [HttpPost]
    //[ValidateAntiForgeryToken]
    public JsonResult PerformImportUsers(List<IFormFile> importFile)
    {
        return new JsonResult(new { result = "success", message = "Uploaded" });
    }

Upvotes: 0

Views: 248

Answers (3)

Ryan
Ryan

Reputation: 20116

First of all, press F12 in browser to check the action (sUrl) is correct or not,it should be action="/Admin/PerformImportUsers".

Then change your js to below to upload files using formdata.You need to match name of formData to the parameter name (importFile)on POST method.

<script>
    $("#uploadFile").on("click", function (e) {
        e.preventDefault();

        var myForm = $("#frmUpload");
        var sUrl = myForm.attr("action");

        var input = document.getElementById("inputGroupFile02");
        var files = input.files;
        var formData = new FormData();

        for (var i = 0; i != files.length; i++) {
            formData.append("importFile", files[i]);
        }


        $.ajax({
            type: "POST",
            url: sUrl,
            contentType: false,
            processData: false,
            data: formData,
            success: function (result) {
                var data = jQuery.parseJSON(result);
                showNotify(data.message);
            },
            error: function () {
                alert("there was an error");
            }
        });
    });
</script>

Upvotes: 1

Eldar
Eldar

Reputation: 10790

    [HttpPost]
        //[ValidateAntiForgeryToken]
        public JsonResult PerformImportUsers() // remove parameter
        {
             var files = this.Request.Form.Files; //retreive files
            return new JsonResult(new { result = "success", message = "Uploaded" });
        }

Besides this code below will only add 1 file

for (var i = 0; i != files.length; i++) {
            formData.append("myfile", files[i]); // change it to "myfile"+i
        }

Upvotes: 1

Matt Kemp
Matt Kemp

Reputation: 2920

To upload a file your form tag needs enctype="multipart/form-data"

Try adding that and you should see the file come through in the back end.

And remove that javascript, that is not needed.

Upvotes: 1

Related Questions