我正在尝试通过 JQuery Ajax 将文件上传到 ASP.NET Core MVC 应用程序。
HttpPostedFileBase
始终为 null
。当我将其作为参数直接放入操作中时,我收到模型绑定(bind)错误。
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.Document
为null
当我将操作重写为以下函数签名时,出现错误:
public IActionResult AddAttachment(int Id, string FileName, System.Web.HttpPostedFileBase Document)
然后我收到以下错误:
An unhandled exception occurred while processing the request. InvalidOperationException: Could not create an instance of type 'System.Web.HttpPostedFileBase'. Model bound complex types must not be abstract or value types and must have a parameterless constructor.
我缺少什么?我希望将文件绑定(bind)在我的模型中,而不是使用 HttpContext.Request.Files
。
最佳答案
你是如何让 HttpPostedFileBase
来解析的?无论如何,它在 ASP.NET Core 中不存在。相反,您应该使用 IFormFile
。
关于c# - 文件上传时 HttpPostedFileBase 始终为 null,模型绑定(bind)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51952363/