Posting files and model to controller in ASP.NET Core MVC6

后端 未结 1 1455
生来不讨喜
生来不讨喜 2021-02-01 09:45

I\'m migrating a project from ASP.NET RC1 to ASP.NET Core 1.0.

I have a view that allows users to upload one of more files, which I post using Jquery Ajax. I also serial

相关标签:
1条回答
  • 2021-02-01 10:29

    I started from this article which has some code that is almost the same as yours Upload Files In ASP.NET Core 1.0 (see Ajax case).

    That worked for me fine on 1.0.0, so I implemented your changes and what I saw is that it failed to send the files in the request (client side issue).

    This is how the payload should look like when working ok using F12 in chrome: (not sure why the file contents are hidden by chrome).

    A little debugging and you are passing wrong data to data.append

    The fix is in this line

            $(".file-select").each(function () { data.append($(this).val(), $(this).get(0).files[0]); i++; })
    

    Full code:

    $(document).ready(function () {
        $("#submit").click(function (evt) {
    
            var data = new FormData();
            i = 0;
    
            $(".file-select").each(function () { data.append($(this).val(), $(this).get(0).files[0]); i++; })
    
            var postData = $('#fields :input');
            $.each(postData, function (key, input) {
                data.append(input.name, input.value);
            });
    
            $.ajax({
                type: "POST",
                url: "/ajax/uploadfile",     // <--- Double check this url.
                contentType: false,
                processData: false,
                data: data,
                success: function (message) {
                    alert(message);
                },
                error: function () {
                    alert("There was error uploading files!");
                }
            });
        });
    });
    

    No need to use [FromBody] or serializeArray()

        [HttpPost]
        public IActionResult UploadFilesAjax(MyViewModel xxx )
        {
    

    This is my html, just in case:

    <form method="post" enctype="multipart/form-data">
    
    <div id="file-list">
        <input type="file" name="file" class="file-select" accept="application/pdf,application">
        <input type="file" name="file" class="file-select" accept="application/pdf,application" />
    </div>
    <div id="fields">
        <input type="text" name="Email" />
    </div>
    
    <input type="button"
            id="submit"
            value="Upload Selected Files" />
    </form>
    
    0 讨论(0)
提交回复
热议问题