2009-09-30 2 views
1

C#에서는 httpwebrequest를 사용하여 웹에서 파일을 dowloading하지 않고 파일에 저장 한 다음 파일을 매개 변수 중 하나로 사용하여 POST를 사용하여 웹 서비스에 업로드합니다.스트리밍을 사용하여 웹 파일을 소스로 사용하여 웹 API에 파일 업로드를 수행 할 수 있습니까?

어떻게 든 httpwebresponse에서 리더 스트림을 연 다음 HTTP POST로 스트리밍합니까? 어떤 코드를 게시하여 어떻게 표시 할 수 있습니까?

즉, 먼저 디스크에 저장하지 않으려 고합니다.

감사

답변

2
트릭을해야 그런

뭔가 :

HttpWebRequest downloadRequest = WebRequest.Create(downloadUri) as HttpWebRequest; 
using(HttpWebResponse downloadResponse = downloadRequest.GetResponse() as HttpWebResponse) 
{ 
    HttpWebRequest uploadRequest = new HttpWebRequest(uploadUri); 
    uploadRequest.Method = "POST"; 
    uploadRequest.ContentLength = downloadResponse.ContentLength; 
    using (Stream downloadStream = downloadResponse.GetResponseStream()) 
    using (Stream uploadStream = uploadRequest.GetRequestStream()) 
    { 
     byte[] buffer = new byte[4096]; 
     int totalBytes = 0; 
     while(totalBytes < downloadResponse.ContentLength) 
     { 
      int nBytes = downloadStream.Read(buffer, 0, buffer.Length); 
      uploadStream.Write(buffer, 0, nBytes); 
      totalBytes += nRead; 
     } 
    } 
    HttpWebResponse uploadResponse = uploadRequest.GetResponse() as HttpWebResponse; 
    uploadResponse.Close(); 
} 

내가 집에있어 다음 업데이트 할 때 (테스트되지 않은 코드)

+0

와우 ... 나는 그것을 밖으로 시도 할 것이다 ... 대단히 감사합니다. – Greg

+0

Hey Thomas -이 문제로 다시 돌아 가기 - 서버가 ContentLength (예 : downloadResponse.ContentLength)를 제공하지 않는 페이지를 대상으로 지정하는 경우 문제가 있음을 알았습니다. "System.NotSupportedException :이 스트림 검색 작업을 지원하지 않습니다 .."얻을 것. 이 문제를 해결하는 방법에 대한 아이디어가 있습니까? – Greg

+0

어떤 명령에서이 예외가 발생합니까? –