2011-05-27 75 views
0

我正在從c#web應用程序進行文件上傳,從客戶端機器轉到遠程雲主機。用戶輸入文件名稱和位置並將其傳遞給服務器。我將文件的內容以塊的形式傳輸到請求中。但是,該文件到達目標時無效。我確定它與我的請求頭文件和垃圾文件有某種關係,因爲我可以在從服務器上傳到遠程位置時使其工作。任何人都可以發現什麼是錯的?從客戶端到webrequest的流文件

while (bytesRemaining > 0) 
{ 
    if (!sw.CanRead) 
    { 
     sw = File.OpenRead(txtFileUpload.Text); 
     if (offset > 0) 
      sw.Seek(offset, SeekOrigin.Begin); 
    } 

    int count = sw.Read(buffer, 0, (int) chunk); 

    request = 
     (HttpWebRequest) 
     WebRequest.Create("http://xxxxxx.com/write/" + 
          offset); 
    request.Method = "POST"; 
    request.ReadWriteTimeout = int.MaxValue; 
    request.Timeout = int.MaxValue; 
    request.KeepAlive = false; 
    string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); 
    request.ContentType = "multipart/form-data; boundary=" + boundary; 

    var postData = new MemoryStream(); 
    const string newLine = "\r\n"; 
    var sw3 = new StreamWriter(postData); 
    sw3.Write("--" + boundary + newLine); 
    sw3.Write("Content-Disposition: form-data;name=\"{0}\";filename=\"{1}\"{2}", "upload", 
       txtFileName.Text, newLine); 
    sw3.Write("Content-Type: multipart/form-data " + newLine + newLine); 
    sw3.Flush(); 

    postData.Write(buffer, 0, count); 
    sw3.Write(newLine); 
    sw3.Write("--{0}--{1}", boundary, newLine); 
    sw3.Flush(); 

    request.ContentLength = postData.Length; 
    using (Stream s = request.GetRequestStream()) 
     postData.WriteTo(s); 

    sw3.Write("--" + boundary + newLine); 
    sw3.Write("Content-Disposition: form-data;name=\"\"" + newLine); 
    sw3.Write("content-type:octet-stream;charset=windows-1250" + newLine); 

    sw3.Write("VALUE" + newLine); 
    sw3.Write("--{0}--{1}", boundary, newLine); 
    sw3.Flush(); 
    postData.Close(); 

    // These next 3 lines are what I had before, instead of all the previous 
    // code, which worked when uploading a file from the server to the remote 
    // location. 
    //using (Stream sw2 = request.GetRequestStream()) 
    //{ 
    // sw2.Write(buffer, 0, count); 
    //} 

    using (WebResponse resp = request.GetResponse()) 
    { 
     resp.Close(); 
    } 

    offset += count; 
    bytesRemaining -= count; 

} 

回答

1

爲什麼要重新發明輪子?使用

WebClient.UploadFile 

http://msdn.microsoft.com/en-us/library/system.net.webclient.uploadfile(v=vs.71).aspx

他們甚至有一個例子。

+0

我需要上傳文件,因爲它們很大(> = 10 GB)。我不認爲WebClient.UploadFile支持。 – user756678 2011-05-27 22:59:45

+0

另外,我需要能夠將授權標頭傳遞給請求。 – user756678 2011-05-27 23:15:35

+0

任何人對此有任何意見?漂亮請! – user756678 2011-05-30 17:34:45