c# - 将文件和模型发布到 ASP.NET Core MVC6 中的 Controller

标签 c# jquery asp.net-mvc asp.net-core asp.net-core-mvc

我正在将一个项目从 ASP.NET RC1 迁移到 ASP.NET Core 1.0。

我有一个 View 允许用户上传一个或多个文件,我使用 Jquery Ajax 发布这些文件。我还在同一篇文章中序列化并发布了一些设置。

以下都适用于 RC1(和 pre-asp.net core):

Js:

    $('#submit').click(function () {      
        var postData = $('#fields :input').serializeArray();
        var fileSelect = document.getElementById('file-select');
        var files = fileSelect.files;

        var data = new FormData();
        for (var i = 0; i < files.length; i++) {
            data.append('file' + i, files[i]);
        }
        $.each(postData, function (key, input) {
            data.append(input.name, input.value);
        });
        var url = '/ajax/uploadfile';
        $.ajax({
            url: url,
            type: "POST",
            contentType: false,
            processData: false,
            cache: false,
            data: data,
            success: function (result) {
                alert('success');                   
            },
            error: function () {
                alert('error'); 
            }
        });
    });

Controller :

  public IActionResult UploadFile(UploadFileModel model)
    {
        var result = new JsonResultData();
        try
        {
            if (Request.Form.Files.Count > 0)
            {
                IFormFile file = Request.Form.Files[0];
                //etc
             }
        }
     }

所以以上不再起作用,没有文件上传,也没有模型绑定(bind)。 我设法解决了一半的问题,所以现在我可以让模型与以下代码绑定(bind)。但是, Controller 仍然会在 Request.Files 上给我一个异常(exception)。我添加了“ header ”属性,并使用了 serializeObject(自定义方法)。在 Controller 中,我添加了 FromBody

Js:

 $('#submit').click(function () {      
        var postData = $('#fields :input').serializeArray();
        var fileSelect = document.getElementById('file-select');
        var files = fileSelect.files;

        var data = new FormData();
        for (var i = 0; i < files.length; i++) {
            data.append('file' + i, files[i]);
        }
        $.each(postData, function (key, input) {
            data.append(input.name, input.value);
        });
        var url = '/ajax/uploadfile';
        $.ajax({
            url: url,
            type: "POST",
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            processData: false,
            cache: false,
            data: serializeAndStingifyArray(data),
            success: function (result) {
                alert('success');                   
            },
            error: function () {
                alert('error'); 
            }
        });
    });

    function serializeAndStingifyArray(array) {
    var o = {};
    var a = array;
    $.each(a, function () {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return JSON.stringify(o);
};

Controller :

    [HttpPost]
    public IActionResult UploadFile([FromBody]UploadFileModel model)
    {
        var result = new JsonResultData();
        try
        {
            if (Request.Form.Files.Count > 0)
            {
                IFormFile file = Request.Form.Files[0];
                //etc
             }
         }
       }

html:

    <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>

最佳答案

我从这篇文章开始,其中一些代码与您的代码几乎相同 Upload Files In ASP.NET Core 1.0 (参见 Ajax 案例)。

这对我来说在 1.0.0 上运行良好,所以我实现了您的更改,但我看到它无法发送请求中的文件(客户端问题)。

这是在 chrome 中使用 F12 正常工作时有效负载的样子:(不确定为什么文件内容被 chrome 隐藏)。

payload

稍微调试一下,您将错误的数据传递给 data.append

修复在这一行

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

完整代码:

$(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!");
            }
        });
    });
});

无需使用[FromBody] 或 serializeArray()

    [HttpPost]
    public IActionResult UploadFilesAjax(MyViewModel xxx )
    {

这是我的 html,以防万一:

<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>

关于c# - 将文件和模型发布到 ASP.NET Core MVC6 中的 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38487452/

相关文章:

c# - C# 的 SDCH 压缩库

javascript在获取新内容时对高度进行动画处理

asp.net-mvc - 对 MVC 5 TextBoxFor、EditFor 和 TextAreaFor 之间的差异感到困惑吗?

.net - 如何在 ASP.NET MVC 中获取当前虚拟路径?

c# - 了解随机二维方向矢量生成

c# - 表单例份验证 : How to handle unauthorized authenticated user

c# - 如果URL包含“#”,如何在C#中获取页面的完整URL?

javascript - 使 Bootstrap Collapse 上的面板标题可点击

javascript - 检查是否输入了正确的电子邮件

asp.net-mvc - 许可证执行系统已被篡改 - win server 2008