我想将错误消息传递给 Blueimp jQuery 文件上传插件。我使用 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 Controller 操作返回 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);
});
}
关于javascript - Blueimp jQuery 文件上传和我的异常(exception),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35304464/