[英]Blueimp jQuery File Upload and my exception
我想将错误消息传递给Blueimp jQuery File Upload插件。 我使用ASP.NET MVC并在出现某些情况时引发我自己的异常(即文件不是真实图像,只有图像异常或图像太宽等)。
var file = Request.Files[i];
_service.ImageValidation(file.InputStream);
public void ImageValidation(System.IO.Stream fileStream)
{
Bitmap bmp = null;
try
{
bmp = new Bitmap(fileStream, false);
}
catch
{
throw new NoImageException();
}
if (bmp.Width > bmp.Height && (bmp.Width < 1024 || bmp.Height < 768))
throw new ImageDimensionTooSmall();
if ((bmp.Width <= bmp.Height) && (bmp.Width < 768 || bmp.Height < 1024))
throw new ImageDimensionTooSmall();
fileStream.Position = 0;
}
在客户端,我尝试通过以下方式捕获错误:
$('#fileupload').fileupload({
url: '/SmartphonePhotographer/ManageFiles?ResponseID=' + ResponseID,
error: function (e, data) {
alert('error');
}
});
“数据”变量始终具有“错误”值。 “ e”具有许多属性,包括statusText =“内部服务器错误”和responseText(带有例外的html页)。 问题-如何在服务器端传递错误消息以在客户端捕获它(也许,错误存在json格式,但是我在文档中找不到它)
转到错误事件,因为您在服务器端代码中引发了异常。 因此,ajax调用获得了500个内部错误响应。
您可以做的是,而不是引发异常,而是返回带有错误消息的json响应。
[HttpPost]
public ActionResult SaveImage()
{
if(IsFileNotValid()) //your method to validate the file
{
var customErrors = new List<string> {"File format is not good",
"File size is too bib"};
return Json(new { Status = "error", Errors = customErrors });
}
//Save/Process the image
return Json ( new { Status="success", Message="Uploaded successfully" });
}
并且在done()
事件中,您可以检查json响应并根据需要显示错误消息。
$('#fileupload').fileupload({
url: '/SmartphonePhotographer/ManageFiles?ResponseID=' + ResponseID,
error: function (e, data,txt) {
alert('error' + txt);
}
}).done(function(response){
if(response.Status==="error")
{
$.each(services.Errors, function (a, b) {
alert(b);
});
}
});
使用这种方法,您可以将多个验证错误发送回客户端,客户端可以对其进行处理(显示给用户?)。
MVC 6
在MVC6中,您可以直接从MVC控制器操作返回HttpStatusCode响应。 因此,您无需自己发送JSON响应。
[HttpPost]
public IActionResult SaveImage()
{
var customErrors = new List<string> { "File format is not good",
"File size is too bib" };
return HttpBadRequest(customErrors);
}
这会将400响应与我们在响应中传递的数据(错误列表)一起发送给调用者。 因此,您可以访问error
事件的错误xHr对象的responseJSON属性以获取它
error: function (a, b, c) {
$.each(a.responseJSON, function (a, b) {
alert(b);
});
}
我同意您的问题是,您抛出异常而不是返回受控响应。 大多数框架会寻找400x或500x的状态码。 因此,您想返回一个友好的json对象和这些范围内的状态代码。 如果这样做,您在错误块中的数据对象将是您返回的内容。
MVC土地:
//get a reference to request and use the below.
return this.Request.CreateResponse(HttpStatusCode.BadRequest, "Your message here");
网络API 2
使用IHttpActionResult
并返回BadRequest("My error message");
如果这样做,它将设置您的状态码并返回响应作为数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.