Windows Client 檔案上傳範例

  • 4491
  • 0

Windows Client 檔案上傳範例, Client 端將多個檔案與POST資料彙整後,透過 httpWebRequest 做上傳程序。

這個範例有 Client 與 Server 兩個專案

1. Client 傳送端:Windows Form 專案,將多個檔案與POST資料彙整後,透過 httpWebRequest 做上傳程序。

2. Server  接收端:ASP.NET 網站 ,以泛型處理常式 (.ashx) 撰寫接收檔案與參數。

 

程式碼主要是參考 stackoverflow 這篇討論: Upload files with HTTPWebrequest (multipart/form-data) 修改而來的。

 

Client 傳送端

在 Windows Client 中上傳檔案時,須要先寫入檔案的標頭資訊,再寫入檔案內容,部份程式碼如下


Stream memStream = new System.IO.MemoryStream();
...
memStream.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";
foreach(FileInfo fi in files)
{
    string header = string.Format(headerTemplate, fi.Name, fi.Name);
    byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
    memStream.Write(headerbytes, 0, headerbytes.Length);
    FileStream fileStream = new FileStream(fi.FullName, FileMode.Open, FileAccess.Read);
                
    byte[] buffer = new byte[1024];
    int bytesRead = 0;
    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
    {
        memStream.Write(buffer, 0, bytesRead);
    }
    memStream.Write(boundarybytes, 0, boundarybytes.Length);
    fileStream.Close();
}

 

Server  接收端

在 Server 端接收處理時,上傳的檔案透過 Request.Files 取得,POST 資料透過 Request.Form 取得。

 

範例下載:請點擊   <----  開發工具為 VS2010, C# , Windows Form + ASP.NET

或者到 https://gist.github.com/robinli/6274401 複製兩段主要處理程序的程式碼。

^_^