如何发布从一个WebForm页面数据到HTTPHandler.ashx文件? [英] How to post data from a webform page to an HTTPHandler.ashx file?

查看:520
本文介绍了如何发布从一个WebForm页面数据到HTTPHandler.ashx文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web应用程序项目,支持文件传输操作,以供应商产品的后端。它的组成与IIS 6.0编译成一个网站Win2003的服务器上2 HttpHandler的文件:


  • UploadHandler.ashx

  • DownloadHandler.ashx

这些文件被贴从一个ColdFusion网站公开用户界面。在某种程度上,因为这些处理器工作,必须从ColdFusion的叫我的任务完成了。

不过,我很沮丧,我无法得到我自己的测试UI(Default.aspx的)在我的测试/细化独立的ColdFusion使用。

 < ASP:按钮的ID =DownloadButton一项PostBackUrl =〜/ DownloadHandler.ashx=服务器文本=下载/>

使用用于下载的一项PostBackUrl很好地工作 - 在进入DownloadHandler.ashx时,它的 context.Request.Form [txtRecordNumber]认定其键输入值;

但我不能使用这种技术用于上传,因为我必须做一些处理的(莫名其妙地读取所选择的fileupload1.postedfile到一个表单变量的字节数,所以我UploadHandler.ashx文件可以从获取其输入的Request.Form与下载)

使用的HttpWebRequest 这似乎过于复杂,我的第一个方法试过,我永远无法得到工作。症状开始与一个HTTP 401状态code,然后演变成一个302状态code所以我研究了其他的想法。

下面是从我的Default.aspx我最近code片断:

 保护无效UploadHandlerButton_Click(对象发件人,EventArgs的发送)
{
    如果(FileUpload1.HasFile)
    {
        尝试
        {
            BuildFormData();
            //Server.Transfer(\"UploadHandler.ashx,真正的);
            的Response.Redirect(〜/ UploadHandler.ashx);
        }
        赶上(例外someError)
        {
            LogText(失败:+ someError.Message);
        }
    }
}
保护无效BuildFormData()
{
    BinaryReader B =新BinaryReader(FileUpload1.PostedFile.InputStream);
    INT的numBytes = FileUpload1.PostedFile.ContentLength;
    字节[] = fileContent b.ReadBytes(的numBytes);
    objBinaryData.Text = System.Text.Encoding.UTF8.GetString(fileContent);
    b64fileName.Text = FileUpload1.PostedFile.FileName;
    //在字符串创建任意元数据
    strMetaData.Text =recAuthorLoc = anyname1〜UDF:OPEAnalyst = anyname2〜UDF:授权号= 0102030405;
}

尝试中的错误使用Server.Transfer的(上面)到我.ashx的文件的结果:
    对于UploadHandler.ashx 错误执行子请求

在尝试当然GET(而不是POST)和的trace.axd使用的Response.Redirect(以上)到我的ashx的文件,结果显示什么表单集合中,这样似乎是错误的了。

我甚至尝试克隆ING我.ashx的文件,并创建UploadPage.aspx(不包括HTML元素一个WebForm),然后尝试:

  Server.Transfer的(UploadPage.aspx,真正的);
//Response.Redirect(\"~/Uplo​​adPage.aspx);

无论是那些让我看到我需要的Request.Form看到我的code处理该上传请求中的表单数据。我清楚地失去了一些东西在这里...感谢您帮助。

修改-UPDATE:
我想我可以澄清我的问题。当UploadHandler.ashx从ColdFusion的发布,它需要的所有输入的可在FORM集合中(例如的Request.Form [FILEDATA]等)

但是,当我使用这个 控制它生成回发到我的启动网页(即Default.aspx的)。这使我受到的 FileUpload1.PostedFile 为手段,指内容:

 保护无效BuildFormData()
{
    BinaryReader B =新BinaryReader(FileUpload1.PostedFile.InputStream);
    INT的numBytes = FileUpload1.PostedFile.ContentLength;
    字节[] = fileContent b.ReadBytes(的numBytes);
    objBinaryData.Text = System.Text.Encoding.UTF8.GetString(fileContent);
    b64fileName.Text = FileUpload1.PostedFile.FileName;
}

但我的不使用的FileUpload1.PostedFile.SaveAs方法来保存文件的地方我的Web服务器上。我需要以某种方式 - 在这里原谅的语言 - 重职这个数据到一个完全不同的文件 - 即,我UploadHandler.ashx处理程序。所有我上面尝试了愚蠢的技术不能完成我需要什么。

修改-UPDATE(20 2009年8月) - 我使用Javascript最终的解决方案:

 保护无效UploadHandlerButton_Click(对象发件人,EventArgs的发送)
{
    如果(FileUpload1.HasFile)
    {
        尝试
        {
            ctlForm.Text = BuildFormData();
            串strJS = InjectJS(_ xclick);
            ctlPostScript.Text = strJS;
        }
        赶上(例外someError)
        {
            LogText(失败:+ someError.Message);
        }
    }
}
私人字符串InjectJS(字符串strFormId)
{
    StringBuilder的strScript =新的StringBuilder();
    strScript.Append(< SCRIPT LANGUAGE =JavaScript的'>中);
    strScript.Append(VAR ctlForm1 = document.forms.namedItem('{0}'););
    strScript.Append(ctlForm1.submit(););
    strScript.Append(&下; /脚本>中);
    返回的String.Format(strScript.ToString(),strFormId);
}
保护字符串BuildFormData()
{
    BinaryReader B =新BinaryReader(FileUpload1.PostedFile.InputStream);
    INT的numBytes = FileUpload1.PostedFile.ContentLength;
    字节[] = fileContent b.ReadBytes(的numBytes);
    //将二进制输入的Base64 UUEn codeD输出。
    串base64String;
    base64String =
           System.Convert.ToBase64String(fileContent,
                                         0,
                                         fileContent.Length);
    objBinaryData.Text = base64String;
    b64fileName.Text = FileUpload1.PostedFile.FileName;
    //在字符串创建任意元数据
    strMetaData.Text =recAuthorLoc =帕特森,弗雷德〜UDF:OPEAnalyst =老虎伍兹〜UDF:授权号= 0102030405;    StringBuilder的strForm =新的StringBuilder();
    strForm.Append(<形式ID = \\_ xclick \\NAME = \\_ xclick \\TARGET = \\_自我\\行动= \\HTTP://localhost/HTTPHandleTRIM/Uplo​​adHandler.ashx \\的方法= \\后\\>中);
    strForm.Append(<输入类型= \\隐藏\\NAME = \\strTrimURL \\价值= \\{0} \\/>中);
    strForm.Append(<输入类型= \\隐藏\\NAME = \\objBinaryData \\价值= \\{1} \\/>中);
    strForm.Append(<输入类型= \\隐藏\\NAME = \\b64fileName \\价值= \\{2} \\/>中);
    strForm.Append(<输入类型= \\隐藏\\NAME = \\strDocument \\价值= \\{3} \\/>中);
    strForm.Append(<输入类型= \\隐藏\\NAME = \\strMetaData \\价值= \\{4} \\/>中);
    strForm.Append(< /形式为GT;);
    返回的String.Format(strForm.ToString()
        ,txtTrimURL.Text
        ,objBinaryData.Text
        ,b64fileName.Text
        ,txtTrimRecordType.Text
        ,strMetaData.Text);
}


解决方案

什么工作对我来说是注入了新的形式和一些JavaScript到表单提交UploadHandler.ashx。这(对我来说)是更容易把握比HttpWebRequest的技术。

I have a web application project to support file transfer operations to vendor product backend. It's composed of 2 HTTPHandler files compiled into a website on a Win2003 server with IIS 6.0:

  • UploadHandler.ashx
  • DownloadHandler.ashx

These files get "POSTed to" from a ColdFusion website that exposes the user interface. In a way, my job is done because these handlers work and have to be called from ColdFusion.

Yet, I am very frustrated with my inability to get my own "test UI" (default.aspx) to use in my testing/refinement independent of ColdFusion.

<asp:Button ID="DownloadButton" PostBackUrl="~/DownloadHandler.ashx"  runat="server" Text="Download"/>

Using a PostBackUrl for Download works nicely - when the DownloadHandler.ashx is entered, it finds its key input value in context.Request.Form["txtRecordNumber"];

But I cannot use this technique for Upload because I have to do some processing (somehow read the bytes from the chosen fileupload1.postedfile into a FORM variable so my UploadHandler.ashx file can obtain its input from Request.Form as with Download).

My first approach tried using HTTPWebRequest which seemed overly complex and I could never get to work. Symptoms began with a HTTP 401 status code and then morphed into a 302 status code so I researched other ideas.

Here is my latest code snippet from my default.aspx:

protected void UploadHandlerButton_Click(object sender, EventArgs e)
{
    if (FileUpload1.HasFile)
    {
        try
        {
            BuildFormData();
            //Server.Transfer("UploadHandler.ashx", true);
            Response.Redirect("~/UploadHandler.ashx");
        }
        catch (Exception someError)
        {
            LogText("FAILURE: " + someError.Message);
        }
    }
}
protected void BuildFormData()
{
    BinaryReader b = new BinaryReader(FileUpload1.PostedFile.InputStream);
    int numBytes = FileUpload1.PostedFile.ContentLength;
    byte[] fileContent = b.ReadBytes(numBytes);
    objBinaryData.Text = System.Text.Encoding.UTF8.GetString(fileContent);
    b64fileName.Text = FileUpload1.PostedFile.FileName;
    // create arbitrary MetaData in a string
    strMetaData.Text = "recAuthorLoc=anyname1~udf:OPEAnalyst=anyname2~udf:Grant Number=0102030405";
}

Attempts to use Server.Transfer (above) to my .ashx file result in an error: error executing child request for UploadHandler.ashx

Attempts to use Response.Redirect (above) to my .ashx file result in GET (not POST) and Trace.axd of course shows nothing in the Form collection so that seems wrong too.

I even tried clone-ing my .ashx file and created UploadPage.aspx (a webform with no HTML elements) and then tried:

Server.Transfer("UploadPage.aspx", true);
//Response.Redirect("~/UploadPage.aspx");

Neither of those allow me to see the form data I need to see in Request.Form within my code that processes the Upload request. I am clearly missing something here...thanks in advance for helping.

EDIT-UPDATE: I think I can clarify my problem. When the UploadHandler.ashx is posted from ColdFusion, all of the input it needs is available in the FORM collection (e.g. Request.Form["fileData"] etc.)

But when I use this control it generates a postback to my launching web page (i.e. default.aspx). This enables me to refer to the content by means of FileUpload1.PostedFile as in:

protected void BuildFormData()
{
    BinaryReader b = new BinaryReader(FileUpload1.PostedFile.InputStream);
    int numBytes = FileUpload1.PostedFile.ContentLength;
    byte[] fileContent = b.ReadBytes(numBytes);
    objBinaryData.Text = System.Text.Encoding.UTF8.GetString(fileContent);
    b64fileName.Text = FileUpload1.PostedFile.FileName;
}

Yet I am not using the FileUpload1.PostedFile.SaveAs method to save the file somewhere on my web server. I need to somehow - forgive the language here - "re-post" this data to an entirely different file - namely, my UploadHandler.ashx handler. All the goofy techniques I've tried above fail to accomplish what I need.

EDIT-UPDATE (20 Aug 2009) - my final SOLUTION using Javascript:

protected void UploadHandlerButton_Click(object sender, EventArgs e)
{
    if (FileUpload1.HasFile)
    {
        try
        {
            ctlForm.Text = BuildFormData();
            String strJS = InjectJS("_xclick");
            ctlPostScript.Text = strJS;
        }
        catch (Exception someError)
        {
            LogText("FAILURE: " + someError.Message);
        }
    }
}
private String InjectJS(String strFormId)
{
    StringBuilder strScript = new StringBuilder();
    strScript.Append("<script language='javascript'>");
    strScript.Append("var ctlForm1 = document.forms.namedItem('{0}');");
    strScript.Append("ctlForm1.submit();");
    strScript.Append("</script>");
    return String.Format(strScript.ToString(), strFormId);
}
protected string BuildFormData()
{
    BinaryReader b = new BinaryReader(FileUpload1.PostedFile.InputStream);
    int numBytes = FileUpload1.PostedFile.ContentLength;
    byte[] fileContent = b.ReadBytes(numBytes);
    // Convert the binary input into Base64 UUEncoded output.
    string base64String;
    base64String =
           System.Convert.ToBase64String(fileContent,
                                         0,
                                         fileContent.Length);
    objBinaryData.Text = base64String;
    b64fileName.Text = FileUpload1.PostedFile.FileName;
    // create arbitrary MetaData in a string
    strMetaData.Text = "recAuthorLoc=Patterson, Fred~udf:OPEAnalyst=Tiger Woods~udf:Grant Number=0102030405";

    StringBuilder strForm = new StringBuilder();
    strForm.Append("<form id=\"_xclick\" name=\"_xclick\" target=\"_self\" action=\"http://localhost/HTTPHandleTRIM/UploadHandler.ashx\" method=\"post\">");
    strForm.Append("<input type=\"hidden\" name=\"strTrimURL\"    value=\"{0}\" />");
    strForm.Append("<input type=\"hidden\" name=\"objBinaryData\" value=\"{1}\" />");
    strForm.Append("<input type=\"hidden\" name=\"b64fileName\"   value=\"{2}\" />");
    strForm.Append("<input type=\"hidden\" name=\"strDocument\"   value=\"{3}\" />");
    strForm.Append("<input type=\"hidden\" name=\"strMetaData\"   value=\"{4}\" />");
    strForm.Append("</form>");
    return String.Format(strForm.ToString()
        , txtTrimURL.Text
        , objBinaryData.Text
        , b64fileName.Text
        , txtTrimRecordType.Text
        , strMetaData.Text);
}

解决方案

What worked for me was to inject a new FORM and some Javascript to submit the FORM to the UploadHandler.ashx. This (for me) was easier to grasp than the HTTPWebRequest technique.

这篇关于如何发布从一个WebForm页面数据到HTTPHandler.ashx文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆