据说Silverlight 4 RC的一个新功能是它现在支持上传进度.
我假设这意味着可以在没有“分块”的情况下制作上传文件进度条,但我无法弄清楚如何做到这一点,那么我们该如何做呢?源代码示例会很棒.
谢谢!
解决方法
好吧,经过大量的游戏,我已经弄明白了:
private void UploadFile(string url,CustomPostDataInfo pdi) { // Use the client http stack! //HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); HttpWebRequest webRequest = (HttpWebRequest)WebRequestCreator.ClientHttp.Create(new Uri(url)); webRequest.AllowWriteStreamBuffering = false; // <-- this enables upload progress reporting! webRequest.Method = "POST"; webRequest.ContentType = "multipart/form-data; boundary=" + pdi.Boundary; // Boundary only needed for multipart form ada // Calculate our response length webRequest.ContentLength = pdi.FormDataHeader.Length + pdi.File2Upload.Length + pdi.FormDataFooter.Length; // Calculate the length of your entire message here,required pdi.request = webRequest; webRequest.BeginGetRequestStream(new AsyncCallback(WritetoStreamCallback),pdi); } private void WritetoStreamCallback(IAsyncResult asynchronousResult) { CustomPostDataInfo pdi = (AmazonS3PostDataInfo)asynchronousResult.AsyncState; HttpWebRequest webRequest = pdi.request; Stream requestStream = webRequest.EndGetRequestStream(asynchronousResult); UTF8Encoding encoding = new UTF8Encoding(); UpdateShowProgress(false,"Uploading file..."); // Your custom update event - make sure to use a dispatcher to update on the UI thread as this is running on a separate thread. // Write any pre file data if needed // ... // Write our file data { // Read chunks of this file byte[] buffer = new Byte[1024 * 32]; Stream fileStream = pdi.File2Upload.OpenRead(); int bytesRead = 0; while ((bytesRead = fileStream.Read(buffer,buffer.Length)) != 0) { requestStream.Write(buffer,bytesRead); requestStream.Flush(); // Will block until data is sent bytesuploaded += bytesRead; //Show the progress change UpdateShowProgress(false,"Uploading file..."); } } // Write any post file data // ... UpdateShowProgress(false,"Uploaded,waiting for response..."); requestStream.Close(); // Get the response from the HttpHandler webRequest.BeginGetResponse(new AsyncCallback(ReadHttpResponseCallback),webRequest); } private void ReadHttpResponseCallback(IAsyncResult asynchronousResult) { HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState; HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult); StreamReader reader = new StreamReader(webResponse.GetResponseStream()); string response = reader.ReadToEnd(); // Get the result reader.Close(); UpdateShowProgress(true,response); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。