2010-03-27 3 views
3

Silverlight 4 RC의 새로운 기능 중 하나는 이제 업로드 진행을 지원한다는 것입니다.업로드 진행 상황 Silverlight 4 RC 파일 업로드 : 방법?

"덩어리"없이 업로드 파일 진행률 표시 줄을 만들 수는 있지만이를 수행하는 방법을 알 수 없다고 가정합니다. 어떻게 처리할까요? 소스 코드 예제가 좋을 것입니다.

감사합니다.

+0

+1, 그게 정말 좋은 질문을. – AnthonyWJones

답변

4

좋아, 연주를 많이 후 나는 그것을 알아 냈있어했습니다

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, 0, buffer.Length)) != 0) 
      { 
       requestStream.Write(buffer, 0, 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); 
    } 
+0

스레드 동기화 로직은 어떻습니까? 아니면이 경우에는 필요하지 않습니까? – jayarjo

+0

나를 위해 모든 것을 메모리에 푸시합니다. 따라서 100MB 파일은 1, 2, 3, 1 초 안에 준비됩니다. BeginGetResponse를 호출하면 실제로 업로드되기 시작합니다. –

+0

불행히도 requestStream.Flush()는 즉시 반환하므로이 코드는 WP7.x에서 작동하지 않습니다. – EvZ

0

this nice article을 살펴 보시기 바랍니다. 이 작업을 수행하는 가장 좋은 방법인지 확실하지 않지만 Silverlight 4에서 MVVM을 사용하는 것이 좋습니다. 이 기사에서는 Silverlight의 비동기 파일 업로드 상태를 표시하는 데 "BusyIndicator"가 사용되는 것을 볼 수 있습니다.

아마도 이것은 도움이 될 것입니다. 실제로 "청킹"동작이 있거나 예상대로 작동하는지는 실제로 알 수 없습니다. 행운을 빕니다!

안부
토마스는

+0

좋은 시작이지만 실제로 업데이트 진행 상황을 제공하지 않습니다. Silverlight 4 RC – steve

+0

이전에 완료되었으므로 코드에 버그가 있습니다. 명확한 설명과 최종 코드 게시에 감사드립니다! – thmshd