웹클라이언트로 데이터서비스 파일업로드 하기

 

버튼클릭시 작동되는 모습 비동기로 업로드하고 있다.

        private void button1_Click(object sender, RoutedEventArgs e)
        {

            var urlString = "http://localhost:51059/WcfDataService1.svc/UploadFile";
            
            var webClient = new WebClient();  

            Debug.WriteLine("업로드 시작");
            webClient.UploadFileAsync(new Uri(urlString) , "POST", @"C:\temp\2pm.mp3");
            webClient.UploadProgressChanged += new UploadProgressChangedEventHandler(webClient_UploadProgressChanged);
            webClient.UploadFileCompleted +=new UploadFileCompletedEventHandler(webClient_UploadFileCompleted);      

        }

UploadProgressChanged는 상태바 표시를 위해 값을 반영하고 있다.

UploadFileCompleted 는 완료되고 나서 작업을 수행 할 수 있다.

        void webClient_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
        {
            // Displays the operation identifier, and the transfer progress.
            Console.WriteLine("{0}    uploaded {1} of {2} bytes. {3} % complete...",
                (string)e.UserState,
                e.BytesSent,
                e.TotalBytesToSend,
                e.ProgressPercentage);
            progressBar1.Value = e.ProgressPercentage;

        }

        void webClient_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
        {            
            
            MessageBox.Show("완료");
        }

 

지금부터는 서버측 DataService 임

소스는 간단하니 보면 다 압니다.

namespace WebApplication1
{
    public class WcfDataService1 : DataService<커스텀Entities>
    {
        // 이 메서드는 서비스 전반적인 정책을 초기화하는 데 한 번만 호출됩니다.
        public static void InitializeService(DataServiceConfiguration config)
        {
            // TODO: 규칙을 설정하여 어떤 엔터티 집합과 서비스 작업을 표시할 수 있고 업데이트할 수 있는지 등을 표시합니다.
            // 예제:
            config.SetEntitySetAccessRule("*", EntitySetRights.All);

            //WebInvoke, WebGet 따로 권한설정
            config.SetServiceOperationAccessRule("ContactidTest", ServiceOperationRights.AllRead); 
            config.SetServiceOperationAccessRule("UploadFile", ServiceOperationRights.All);
            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
        }

        [WebInvoke]
        public void UploadFile()
        {
            if (HttpContext.Current != null)
            {
                var request = HttpContext.Current.Request;

                for (int i = 0; i < request.Files.Count; i++)
                {
                    var file = request.Files[i];
                    var inputValues = new byte[file.ContentLength];

                    using (var requestStream = file.InputStream)
                    {
                        requestStream.Read(inputValues, 0, file.ContentLength);
                    }

                    File.WriteAllBytes(@"c:\temp\server\" + file.FileName, inputValues);
                 }
            }
        } 
    }
}

4메가 이상 또 안올라간다.! 딱 봐도 설정문제임

넉넉하게 줬다.

<httpRuntime  maxRequestLength="302100" ></httpRuntime>

 

그래도 안올라감! 데이터서비스의 바인딩값을 높였다. 잘됨

<system.serviceModel>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
  <services>
    <service name="WebApplication1.WcfDataService1">
      <endpoint binding="webHttpBinding" bindingConfiguration="higherMessageSize" contract="System.Data.Services.IRequestHandler">
      </endpoint>
    </service>  
  </services>
  <bindings>
    <webHttpBinding>
      <binding name="higherMessageSize" openTimeout="00:10:00" maxBufferSize="65536" maxBufferPoolSize="65536" maxReceivedMessageSize="500000000" transferMode="Streamed">
        <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
      </binding>
      <binding name="NewBinding0" />
    </webHttpBinding>
  </bindings>
</system.serviceModel>

+ Recent posts