【发布时间】:2017-09-17 18:55:12
【问题描述】:
我正在使用 ajax 和 html 文件选择器将文件上传到我的 Web APi(在 c#、ASP.NET 中)。我有一个视图模型,我想使用我的视图模型将文件传递给我的控制器。
这是我的代码: 我的视图模型
public class CursoViewModel
{
public Guid CursoId { get; set; }
[MaxLength(125)]
public string Titulo { get; set; }
public string Descripcion { get; set; }
[Required(ErrorMessage ="select image file for course")]
[DataType(DataType.Upload)]
public HttpPostedFileBase Imagen { get; set; } //note this is the image
}
我的看法,
<form id="Editcurso" method="post" action="#" enctype="multipart/form-data">
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "Please fix the following errors.")
<div class="container">
<div class="form-group">
@Html.LabelFor(c=>c.Titulo)
@Html.TextBoxFor(c => c.Titulo, new { @class="form-control"})
@Html.ValidationMessageFor(m => m.Titulo)
</div>
<div class="form-group">
@Html.LabelFor(c => c.Descripcion)
@Html.TextAreaFor(c => c.Descripcion, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Descripcion)
</div>
<div class="form-group">
@Html.LabelFor(m => m.Imagen)
@Html.TextBoxFor(m => m.Imagen, new {type = "file"})
@Html.ValidationMessageFor(m => m.Imagen)
</div>
<button id="submiter" type="submit" class="btn btn-primary">Listo!</button>
</div>
我的javascript:
$('#Editcurso').submit(function(e) {
e.preventDefault(); // prevent the default submit
if (!$(this).valid()) {
return; // exit the function and display the errors
}
jQuery.support.cors = true;
var data = new FormData();
var files = $("#Imagen").get(0).files;
// Add the uploaded image content to the form data collection
if (files.length > 0) {
data.append("UploadedImage", files[0]);
console.log("files uploaded");
}
var viewmodel = new Object();
viewmodel.Titulo = "Sourav";
viewmodel.Descripcion = "Kayal";
viewmodel.CursoId = "some guid";
viewmodel.Imagen = files; /*<<==I pass the file here*/
$.ajax({
url: '/api/ProfesorCurso/test',
type: 'PUT',
dataType: 'json',
data: viewmodel,
success: function (data) {
console.log(data);
return false;
},
error: function (x, y, z) {
alert('error al postear');
return false;
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
我的 api
[HttpPut]
public IHttpActionResult UpdateCursoProfesor([FromBody] CursoViewModel viewmodel)
{
if (!ModelState.IsValid) return BadRequest();
try
{
//do something, upload the file inside the viewmodel
return Ok(result);
}
catch (DbEntityValidationException e)
{ //do something}
当我执行我的程序时,我收到以下错误消息:“Uncaught TypeError: Illegal invocation”。我究竟做错了什么?谢谢
【问题讨论】:
-
将 HttpPostedFileBase 更改为字节数组或 base64 字符串
-
你好,你能加我一个代码示例吗?以及如何恢复文件?谢谢
-
您需要设置正确的 ajax 选项,但您也可以通过仅使用
var formdata = new FormData($('form').get(0));来简化此操作 - 请参阅 this answer -
@StephenMuecke 我试过了,但是当传递给 api 操作时,formdata 为空。我也试过这样做 var formdata = new FormData($('#MyForm').get(0));
-
那我只能假设你没有设置正确的 ajax 选项。
标签: javascript c# jquery ajax asp.net-mvc