使用SilverLight应用程序中的HTTPWebrequest上传文件(为什么内容长度为13?)

时间:2011-06-21 11:08:14

标签: silverlight silverlight-4.0 file-upload httpwebrequest

友! 请帮帮我!

我尝试从Silverlight发布文件。我使用这样的课程:

public class HttpHelper
    {
        public WebRequest Request { get; set; }
        public Stream Filestream { get; private set; }

        public HttpHelper(Stream filestream)
        {            
            Request = WebRequest.Create("http://www.mysite.com/recieve");                
            Request.Method = "POST";
            Request.ContentType = "application/octet-stream";
            Filestream = filestream;
        }

        private static void BeginFilePostRequest(IAsyncResult ar)
        {
            HttpHelper helper = ar.AsyncState as HttpHelper;
            if (helper != null)
            {
                byte[] bytes = new byte[helper.Filestream.Length];
                int sf = helper.Filestream.Read(bytes, 0, (int)helper.Filestream.Length);
                //helper.Request.ContentLength = bytes.Length; //It doesn't work in SL
                using (StreamWriter writer = new StreamWriter(helper.Request.EndGetRequestStream(ar)))
                {
                    writer.Write(bytes);
                }
                helper.Request.BeginGetResponse(new AsyncCallback(HttpHelper.BeginResponse), helper);
            }
        }

        private static void BeginResponse(IAsyncResult ar)
        {
            HttpHelper helper = ar.AsyncState as HttpHelper;
            if (helper != null)
            {
                HttpWebResponse response = (HttpWebResponse)helper.Request.EndGetResponse(ar);
                if (response != null)
                {
                    Stream stream = response.GetResponseStream();
                    if (stream != null)
                    {
                        using (StreamReader reader = new StreamReader(stream))
                        {
                            //anything...
                        }
                    }
                }
            }
        }

        public void PostFile()
        {            
            this.Request.BeginGetRequestStream(new AsyncCallback(HttpHelper.BeginFilePostRequest), this);
        }
    }

我在Silverlight应用程序中有Stream并尝试通过单击提交按钮调用PostFile:

private void submit_button_Click(object sender, RoutedEventArgs e)
        {           
            //...         
            HttpHelper helper = new HttpHelper(memory_stream);
            helper.PostFile();
        }

但是mysite收到了没有文件的请求。它只有ContentLength 13.有什么问题?

2 个答案:

答案 0 :(得分:0)

在退出using块之前尝试刷新您的作家,您还应该从Close检索到的流上调用EndGetRequestStream

答案 1 :(得分:0)

您必须刷新并处理HTTP请求流和所有下游流,然后才能正常工作。