【问题标题】:How to deal file upload error with XmlHttpRequest and asp.net mvc?如何使用 XmlHttpRequest 和 asp.net mvc 处理文件上传错误?
【发布时间】:2014-11-28 07:49:21
【问题描述】:

为简单起见:

客户:

var xrh = new XmlHttpRequest();
...
xrh.onerror = on_upload_error;
xrh.send(...)

服务器:

public class file_transfer
{
    [HttpPost]
    public void Upload(HttpPostedFileBase[] files_to_upload)
    {
        ...
        if (succeeded)
        {
            // what should I to to let the client know the success? in onload
        }
        else
        {
            // what should I to to let the client know the failaure? maybe in onerror
        }
    }
}

我应该怎么做才能让客户知道成功?正在加载中?

我应该怎么做才能让客户知道失败?可能是onerror?

【问题讨论】:

    标签: javascript ajax asp.net-mvc upload


    【解决方案1】:

    您可以向客户端返回http成功/失败代码:

    [HttpPost]
    public ActionResult Upload(HttpPostedFileBase[] files_to_upload)
    {
        ...
        if (succeeded)
        {
            return new HttpStatusCodeResult(200);
        }
        else
        {
            return new HttpStatusCodeResult(400);
        }
    }
    

    【讨论】:

    • 你需要遵循 asp.net mvc 约定,控制器类必须以 'Controller' 结尾。比如AccountController
    • 这些json结果是否绑定到XmlHttpRequest中的onerror和onload?
    • 是的,应该是 UploadController(...) 而不是 Upload(...)
    • 如果你想绑定onerror和onload,json结果不正确。这种情况下可以使用HttpStatusCodeReuslt,成功返回2xx码,失败返回4xx或5xx码
    • 谢谢。我想看到错误信息,所以想返回一个JsonResult,但是如何在客户端获取JsonResult? on_load(evt) 被调用,但是 evt.status 没有定义。
    猜你喜欢
    • 1970-01-01
    • 2014-03-14
    • 1970-01-01
    • 2021-03-05
    • 2011-07-08
    • 2011-08-16
    • 2017-09-25
    • 1970-01-01
    • 2010-09-16
    相关资源
    最近更新 更多