简体   繁体   English

在javascript中将文本上传到asp.net通用处理程序

[英]Upload text to an asp.net generic handler in javascript

How can I upload text written by the user to an asp.net generic handler? 如何将用户编写的文本上传到asp.net通用处理程序? the text is pretty lengthy. 文字相当冗长。

Looking at the code from your comment (thanks for sharing), it seems like the parameter containing your text is called data in your JavaScript and you are looking for file in your handler. 查看评论中的代码(感谢分享),似乎包含文本的参数在JavaScript中称为data ,并且您正在寻找处理程序中的file

Try: context.Request.Form["data"] in your handler. 尝试:处理程序中的context.Request.Form["data"]

Try some jQuery code like this: 尝试一些像这样的jQuery代码:

jQuery(document).ready(function($){
    $('#button-id-to-submit-info-to-the-handler').on('click', function(ev) {
        ev.preventDefault();

        //Wrap your msg in some fashion
        //in case you want to end other things
        //to your handler in the future
        var $xml = $('<root />')
            .append($('<msg />', { 
                text: escape($('#id-of-your-textarea-that-has-the-text').val()) 
            }
        ));

        $.ajax({
            type:'POST',
            url:'/path/to-your/handler.ashx',
            data: $('<nothing />').append($xml).html(),
            success: function(data) {
                $('body').prepend($('<div />', { text: $(data).find('responsetext').text() }));
            }
        });
    });
});

And in your handler: 在你的处理程序中:

public class YourHandler : IHttpHandler
{
   public void ProcessRequest(HttpContext ctx)
   {
       //Response with XML
       //Build a response template
       ctx.Response.ContentType = "text/xml";
       String rspBody = @"<?xml version=\""1.0\"" encoding=\""utf-8\"" standalone=\""yes\""?>
<root>
    <responsetext>{0}</responsetext>
</root>";

      //Get the xml document created via jquery
      //and load it into an XmlDocument
      XmlDocument xDoc = new XmlDocument();
      using (System.IO.StreamReader sr = new StreamReader(ctx.Request.InputStream))
      {
         String xml = sr.ReadToEnd();
         xDoc.LoadXml(xml);
      }

      //Find your <msg> node and decode the text
      XmlNode msg = xDoc.DocumentElement.SelectSingleNode("/msg");
      String msgText = HttpUtility.UrlDecode(msg.InnerXml);
      if (!String.IsNullOrEmpty(msgText))
      {
          //Success!!
          //Do whatever you plan on doing with this
          //and send a success response back
          ctx.Response.Write(String.Format(rspBody, "SUCCESS"));
      }
      else
      {
          ctx.Response.Write(String.Format(rspBody, "FAIL: msgText was Empty!"));
      }
   } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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