【问题标题】:Blueimp jQuery File Upload and my exceptionBlueimp jQuery 文件上传和我的例外
【发布时间】:2026-02-11 08:50:02
【问题描述】:

我想将错误消息传递给 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');
            }
        });

'data' 变量总是有 'error' 值。 'e' 有很多属性,包括 statusText='Internal server error' 和 responseText(html 页面异常)。问题 - 如何在服务器端传递错误消息以在客户端捕获它(也许,有一个 json 格式的错误,但我没有在文档中找到它)

【问题讨论】:

    标签: javascript jquery asp.net-mvc blueimp


    【解决方案1】:

    因为您在服务器端代码中引发了异常,所以它会转到错误事件。所以 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);
         });
     }
    

    【讨论】:

    • 如果您将响应代码设置为错误请求,我会投赞成票...这将迫使上传者进入错误块。我不喜欢强迫人们检查布尔值是否成功/失败,因为大多数框架都会提示 http 状态代码。
    • 我认为他想以 json 格式发送他的自定义错误消息,以便他可以将其显示给用户。我不确定只发送一个错误的请求响应是否会有所帮助。
    • 但是这个控件需要github.com/blueimp/jQuery-File-Upload/wiki/JSON-Response格式的json。但无论如何,谢谢你:)
    • @Nix 你是对的,在 MVC 6 中,我们可以从操作方法返回状态代码响应(带有自定义响应)(就像我们之前对 Web api 所做的那样)。
    【解决方案2】:

    我同意您的问题是您抛出异常而不是返回受控响应。大多数框架在 400x 或 500x 中寻找状态码。因此,您希望返回一个友好的 json 对象和这些范围内的状态代码。如果你这样做,你在错误块中的数据对象将是你返回的。

    MVC 土地:

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

    Web API 2

    使用IHttpActionResult 并返回BadRequest("My error message"); 如果您这样做,它将设置您的状态代码并将响应作为数据返回。

    【讨论】:

    • return new HttpResponseMessage(HttpStatusCode.BadRequest, "Your message here"); - 你在哪里找到带有 2 个参数的 HttpResponseMessage 构造函数? :)
    • 我认为在旧版本的 mvc 中你可以做到这一点......也许是 4 个?但无论哪种方式,您都可以使用CreateResponse 来实现相同的效果。
    最近更新 更多