简体   繁体   中英

Blueimp jQuery File Upload and my exception

I want to pass error message to Blueimp jQuery File Upload plugin. I use ASP.NET MVC and throw my own exception when some conditions are appeared (ie file is not real image, only image exception or image is too wide etc).

                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;
    }

on client side I try to catch error by the following way:

        $('#fileupload').fileupload({
            url: '/SmartphonePhotographer/ManageFiles?ResponseID=' + ResponseID,
            error: function (e, data) {
                alert('error');
            }
        });

'data' variable always has 'error' value. 'e' has many properties, including statusText='Internal server error' and responseText (html page with exception). Question - how can I pass error message on server side to catch it on client side (maybe, there is an json format for errors, but I did not find it in documentation)

It goes to the error event because you are throwing an exception in your server side code. So the ajax call is getting a 500 internal error response.

What you can do is, instead of throwing an exception, return a json response with the error messages.

[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" });
}

And in the done() event, you can inspect the json response and show the error messages as needed.

$('#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);
       });
   }       
});

With this approach, you can send multiple validation errors back to the client and client can process(show to user ?) it.

MVC 6

In MVC6, you can return an HttpStatusCode response directly from the MVC controller action. So no need to send a JSON response yourself.

 [HttpPost]
 public IActionResult SaveImage()
 {
     var customErrors = new List<string> { "File format is not good", 
                                            "File size is too bib" };

     return HttpBadRequest(customErrors);
 }

This will send a 400 Response to the caller with the data we passed(the list of errors) in the response. So you can access the responseJSON property of your error xHr object of the error event to get it

error: function (a, b, c) {           
     $.each(a.responseJSON, function (a, b) {
            alert(b);
     });
 }

I agree your issue is that you are throwing an exception versus returning a controlled response. Most frameworks look for status codes in the 400x or 500x. So you want to return a friendly json object and a status code in those ranges. If you do that your data object in the error block will be what you returned.

MVC Land:

//get a reference to request and use the below.
return this.Request.CreateResponse(HttpStatusCode.BadRequest, "Your message here");

Web Api 2

Use an IHttpActionResult and return BadRequest("My error message"); If you do that it will set your status code and return the response as the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM