[英]ajax send file to mvc api c# :Uncaught TypeError: Illegal invocation
我正在使用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}
調用$.ajax
方法通過FormData
發送文件時,需要將processData
和contentType
屬性值指定為false。
var url ='/api/ProfesorCurso/test';
$.ajax({
url: url,
type: 'PUT',
data: viewmodel,
processData: false,
contentType: false,
success: function (data) {
console.log(data);
return false;
},
error: function (x, y, z) {
alert('error al postear');
return false;
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.