使用http-post将xml文件发送到处理程序

时间:2011-10-19 13:59:48

标签: c# asp.net post handler

    protected void UploadFile(object sender, EventArgs e)
    {
        if (fileUpload.HasFile)
        {
            if (fileUpload.PostedFile.ContentType == "text/xml")
            {
                Stream inputstream = fileUpload.PostedFile.InputStream;

                byte[] streamAsBytes = (ConvertStreamToByteArray(inputstream));

                string stringToSend = BitConverter.ToString(streamAsBytes);

                xmlstream.Value = stringToSend;

                sendXML.Visible = true;
                infoLabel.Text = string.Empty;
/*
                string path = Server.MapPath("GenericHandler.ashx");
                WebClient wc = new WebClient();
                wc.UploadFile(path,"POST", fileUpload.PostedFile);
                 Something like this maybe? But is there any way to do it without saving the file?            */

            }
            else
            {
                infoLabel.Text = "Please select an XML file";
                sendXML.Visible = false;
            }
        }
    }

这是我目前的代码。 xml作为十六进制字符串保存在隐藏字段中,并通过jquery ajax发送。但是发送文件本身并在处理程序中处理它会好得多。这可能吗?

2 个答案:

答案 0 :(得分:0)

是的,您可以创建HttpWebRequest,将其设置为MethodPOST(如果这是您需要的),然后使用您的文件数据在请求中创建表单字段。您需要了解一下HTTP请求的工作原理以及如何在请求中正确创建该表单字段,但这是可行的(并且不是太难)。

答案 1 :(得分:0)

尝试下面的代码,我没有测试它但它应该工作,而不是字符串传递byte []到方法

    private string PostData(string url, byte[] postData)
    {
        HttpWebRequest request = null;
        Uri uri = new Uri(url);
        request = (HttpWebRequest)WebRequest.Create(uri);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = postData.Length;
        using (Stream writeStream = request.GetRequestStream())
        {
            writeStream.Write(postData, 0, postData.Length);
        }
        string result = string.Empty;
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            using (Stream responseStream = response.GetResponseStream())
            {
                using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
                {
                    result = readStream.ReadToEnd();
                }
            }
        }
        return result;
    }

Http Post in C#

找到代码