【问题标题】:return response back to ajax from ashx handler in c#从 c# 中的 ashx 处理程序将响应返回给 ajax
【发布时间】:2016-10-14 11:07:48
【问题描述】:

在我的应用程序中,我使用一个 ashx 处理程序来下载 ppt,因为我将创建一个屏幕截图(当前屏幕作为图像)并将该图像名称从 jquery 传递给一个处理程序(ashx)。但我无法跟踪下载状态。

如果有任何方法可以将该处理程序的响应返回给 jquery。那就是我想知道下载什么时候完成。

我现在的情况是这样的

  1. jquery 将生成一个 base64 字符串并通过 ajax 调用将该字符串传递给后面的代码,以将其转换为图像并将该图像保存在一个位置

  2. 在成功调用该 ajax 请求时,它将获取该图像名称并将该图像名称传递给处理程序

  3. 我正在使用“window.location.href”调用该处理程序

我的代码

Ajax 调用保存图片

   $.ajax({
            type: "POST",
            url: AQ.AMT.Url + "/Home/StoreImage",
            //async: false,
            data: "{'base64':'" + base64 + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (Data) {
                window.location.href = "~/Download/Export.ashx?Type=PPT&downloadToken=" + Data.Result + "&Summary=" + summaryText + "&Note=" + noteText + "&Name=" + name + "&Sample=" + sampleSize + "&SampleColor=" + sampleColor + "&pptType=" + pptType + "&flipName=" + flipName;
              //here i need some response
            },
            error: function (e) {
            }
        });

下载ppt的处理程序代码

 public void ProcessRequest(HttpContext context)
    {
        DownloadPPT(context);
    }
 public void DownloadPPT(HttpContext context)
    {
      //here i will take all parameters 
      try{
          //downloading the ppt
          saveFile(pres, "" + name + "-" + FlipName + "-" + System.DateTime.Today.ToLongDateString());//ppt name
         }
        catch{

             }
          finally
            {
            //after ppt download i am deleting that screenshot
            if (File.Exists(path))
                File.Delete(path);

             }  
    }

【问题讨论】:

    标签: asp.net ajax post httphandler ashx


    【解决方案1】:

    我有一个解决方案,而不是使用处理程序来下载我使用 ajax 和 jquery 的文件。在这后面的代码中,我将创建 ppt 并将 ppt 保存在某个文件夹中,然后我将该名称传递给 ajax 响应并使用锚标记来启用客户端本身的下载。

    保存ppt

     [HttpPost]
        public JsonResult StoreImage(ExportToPPtRequest request)
        {
            ExportPptString obj = new ExportPptString();
            string downloadToken = Guid.NewGuid().ToString();
            string filepath = Server.MapPath("~/Download/Temp/" + downloadToken + ".png");
            try
            {
                using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(request.Base64)))
                {
                    using (System.Drawing.Bitmap bm2 = new System.Drawing.Bitmap(ms))
                    {
                        //bm2.Save(filepath);
    
                        downloadToken = "";
    
                        downloadToken=DownloadPPT(bm2,request);
                       // bm2.Dispose();
                    }
                   // ms.Close();
                }
    
                obj.Result = downloadToken;
    
            }
            catch (Exception ex)
            {
    
            }
            var result = Json(obj, JsonRequestBehavior.AllowGet);
            return result;
        }
    
        public string DownloadPPT(Image imgToReplace, ExportToPPtRequest request)
        {
    
             string summaryText = request.Summary;
             string note = request.Note;
             string sampleSize = request.SampleSize;
             string SampleColor = request.SampleColor;
             string Type = request.Type;
             string name = request.Name;
             string pptName = "";
             try
            {
                //if (downloadToken == string.Empty || downloadToken == null)
                //    throw new Exception("Download Token is unavailable.");
    
                Aspose.Slides.License license = new Aspose.Slides.License();
                license.SetLicense("Aspose.Slides.lic");
                var _tempPPT = "";
                    _tempPPT = Server.MapPath("~/Download/Template/ExportPPt.pptx");
    
                Aspose.Slides.Presentation pres = new Aspose.Slides.Presentation(_tempPPT);
    
    
              pptName= saveFile(pres);//ppt name
    
            }
            catch (Exception ex)
            {
    
            }
    
            return pptName;
    
        }
        public  string saveFile(Aspose.Slides.Presentation pres)
        {
    
            string downloadToken = Guid.NewGuid().ToString();
            try
            {
                //MemoryStream objMemoryStream = new MemoryStream();
                //pres.Save(objMemoryStream, Aspose.Slides.Export.SaveFormat.Pptx);
                pres.Save(Server.MapPath("~/Download/Temp/" + downloadToken + ".pptx"), Aspose.Slides.Export.SaveFormat.Pptx);
                //byte[] buffer = objMemoryStream.ToArray();
                //HttpContext.Current.Response.Clear();
                //HttpContext.Current.Response.Buffer = true;
                //HttpContext.Current.Response.AddHeader("Content-disposition", String.Format("attachment; filename=\"{0}.pptx\"", PresentationName));
                //HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
                //HttpContext.Current.Response.AddHeader("Content-Length", buffer.Length.ToString());
                //HttpContext.Current.Response.BinaryWrite(buffer);
                //HttpContext.Current.Response.Flush();
                //HttpContext.Current.Response.Close();
    
    
            }
            catch (Exception ex)
            {
            }
            return downloadToken;
        }
    

    在 jquery 中

    $.ajax({
            type: "POST",
            url: AQ.AMT.Url + "/Home/StoreImage",
            //async: false,
            data: JSON.stringify({ request: request }),
            contentType: "application/json; charset=utf-8",
            dataType: "json", 
            success: function (Data) {
    
                var _tempPPT = AQ.AMT.Url + "/Download/Temp/" + Data.Result + ".pptx";
                // Trick for making downloadable link
                a = document.createElement('a');
                a.href = _tempPPT;// window.URL.createObjectURL(xhttp.response);
                a.id = "idanchrPPT";
                // Give filename you wish to download
                var today = new Date();
                var dd = today.getDate();
                var mm = today.getMonth() + 1; //January is 0!
                var yyyy = today.getFullYear();
                if (dd < 10) {
                    dd = '0' + dd
                }
                if (mm < 10) {
                    mm = '0' + mm
                }
                today = dd + '/' + mm + '/' + yyyy;
                if (flipName == "")
                    a.download = "" + name + "-" + today + ".pptx";
                else
                a.download = "" + name + "-" + flipName + "-" + today + ".pptx";
                a.style.display = 'none';
                document.body.appendChild(a);
                a.click();
                $("#idanchrPPT").remove();
    
    
                //deleting the file
                var deleteFiles = {};
                deleteFiles.FilePath = Data.Result;
                setTimeout(function () {
                    $.ajax({
                        type: "Post",
                        data: JSON.stringify({ deleteFiles: deleteFiles }),
                        url: AQ.AMT.Url + "/Home/DeleteExportedPPt",
                        async: true,
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (result) {
                        },
                        error: function (result) {
                        }
                    });
                }, 1000);
            },
            error: function (e) {
            }
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-01
      • 1970-01-01
      • 2015-04-29
      • 1970-01-01
      • 2016-05-24
      • 1970-01-01
      • 1970-01-01
      • 2013-01-09
      相关资源
      最近更新 更多