通过将文件上载到ASHX处理程序来实现SSE(服务器发送的事件)

Implement SSE (Server Sent Events) with File Upload to ASHX Handler

本文关键字:服务器 SSE 事件 实现 文件 上载 程序 处理 ASHX      更新时间:2023-09-26

我想实现以下内容:

  1. 使用Jquery从UI调用ASHX hanlder
  2. 将文件上载到此ASHX处理程序
  3. 上传完成后,我想继续从服务器向UI(SSE)发送消息,告诉用户ASHX处理程序中代码的执行状态

我被上面提到的第三点卡住了。

以下是我写的UI代码:

     var file = $("input#importFileInputHidden")[0].files[0];
     var formData = new FormData();
     formData.append('file', file);
     importAjaxCall = $.ajax({
        xhr: function () {
            var xhr = new window.XMLHttpRequest();
            $('#progressBar').show();
            //Method to show the progress of the file being uploaded
            xhr.upload.addEventListener("progress", function (evt) {
                if (evt.lengthComputable) {
                    var percentComplete = Math.round((evt.loaded / evt.total) * 100);
                    $('#percentageImportComplete').text('' + percentComplete + '%');
                    $('#importStatus').css('width', percentComplete + '%');
                }
            }, false);
            return xhr;
        },
        type: 'post',
        url: "Handler.ashx",
        data: formData,
        processData: false,
        contentType: false,
        success: function (data) {
            //Some code to show success status to user
    });

如何捕获我从服务器发送的消息?

是否尝试过查看http请求的responseText属性?

success: function () {
            console.log(xhr.responseText);
    });