【问题标题】:HttpPostedFileBase always null on file upload, model bound errorHttpPostedFileBase 在文件上传时始终为空,模型绑定错误
【发布时间】:2018-08-24 22:06:26
【问题描述】:

我正在尝试通过 JQuery Ajax 将文件上传到 ASP.NET Core MVC 应用程序。

HttpPostedFileBase 始终为null。当我将它作为参数直接放在操作中时,我遇到了模型绑定错误。

Javascript:

$(document).on('click', '#attachItemBtn', function () {
    var attachItemFiles = document.getElementById('attachItemFile');

    var formData = new FormData();
    formData.append("Document", attachItemFiles.files[0]);
    formData.append("Id", 1234);
    formData.append("FileName", "test");

    $.ajax({
        cache: false,
        type: "POST",
        data: formData,
        processData: false,
        contentType: 'multipart/form-data',
        url: App.Urls.AddAttachment,
        success: function (data) {
            App.Messages.showErrorMessage('Item attached');
        },
        error: function (xhr, ajaxOptions, thrownError) {
            App.Messages.showErrorMessage('Error Occured While attaching document');
        }
    });

    var debug = 0;
});

行动:

[HttpPost]
public IActionResult AddAttachment(AttachmentItemModel model)
{
    var count = HttpContext.Request.Form.Files.Count;
    int i = 0;
    return Json("done");
}

型号:

public class AttachmentItemModel
{
    public int Id { get; set; }
    public HttpPostedFileBase Document { get; set; }
    public string FileName { get; set; }
}

上面的代码适用于HttpContext.Request.Form.Files,但model.Documentnull

当我将 Action 重写为以下函数签名时,我得到一个错误:

public IActionResult AddAttachment(int Id, string FileName, System.Web.HttpPostedFileBase Document)

然后我得到以下错误:

处理请求时发生未处理的异常。 InvalidOperationException:无法创建类型的实例 'System.Web.HttpPostedFileBase'。模型绑定的复杂类型不得 抽象或值类型,并且必须有一个无参数的构造函数。

我缺少什么?我希望将文件绑定到我的模型中,而不是使用HttpContext.Request.Files

【问题讨论】:

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


    【解决方案1】:

    你是如何让HttpPostedFileBase 解决的?无论如何,它在 ASP.NET Core 中不存在。相反,您应该使用IFormFile

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多