[C#][ASP.net] 透過 HttpWebRequest 模擬Client上傳檔案

2012-11-22

 

事情是這樣子的(抖哥如是說),因為常常會跟其他開發技術合作像是 JSP or PHP ..

他們會跟你說我們上傳檔案是這樣子的..然後給你一個Sample Code :

Client :


<form action = "http://192.168.1.100/uploadFile.jsp"
method="post" enctype="multipart/form-data">
Desc : <input type="text" name="iptDesc">
<br>
<input type="file" name="uploadFileName" />
<input type="submit" value="上傳" />
</form>


實際上,他可能是在Server這邊的內網,那我該如何這邊透過Server 端 把使用者傳給我的圖片上傳給他呢?!
這時候要透過 HttpWebRerequest 來做


 
 
 
/// <summary>
/// 上傳檔案至 Server 透過HttpWebRequest
/// </summary>
/// <param name="url">上傳網址</param>
/// <param name="file">檔案位置</param>
/// <param name="paramName">該control name</param>
/// <param name="contentType">image type </param>
/// <param name="nvc">其他參數</param>
/// <returns></returns>
public string UploadFileByHttpWebRequest(string url, string file, string paramName, string contentType, NameValueCollection nvc)
{
 
   // Debug.WriteLine(string.Format("上傳至 {0} to {1}", file, url));
  
    string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
    byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
 
    HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
    wr.ContentType = "multipart/form-data; boundary=" + boundary;
    wr.Method = "POST";
    wr.KeepAlive = true;
    wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
 
    Stream rs = wr.GetRequestStream();
 
    string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
    foreach (string key in nvc.Keys)
    {
        rs.Write(boundarybytes, 0, boundarybytes.Length);
        string formitem = string.Format(formdataTemplate, key, nvc[key]);
        byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
        rs.Write(formitembytes, 0, formitembytes.Length);
    }
    rs.Write(boundarybytes, 0, boundarybytes.Length);
 
    string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
    string header = string.Format(headerTemplate, paramName, file, contentType);
    byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
    rs.Write(headerbytes, 0, headerbytes.Length);
 
    FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
    byte[] buffer = new byte[4096];
    int bytesRead = 0;
    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
    {
        rs.Write(buffer, 0, bytesRead);
    }
    fileStream.Close();
 
    byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
    rs.Write(trailer, 0, trailer.Length);
    rs.Close();
 
    WebResponse wresp = null;
    var result = "";
    try
    {
        wresp = wr.GetResponse();
        Stream stream2 = wresp.GetResponseStream();
        StreamReader reader2 = new StreamReader(stream2);
        //成功回傳結果
        result = reader2.ReadToEnd();
        
        //File.WriteAllText(Server.MapPath("log.txt"), string.Format("Server 回應{0}", reader2.ReadToEnd()));
    }
    catch (Exception ex)
    {
 
       // File.WriteAllText(Server.MapPath("log.txt"), string.Format("上傳失敗,錯誤訊息: {0}", ex.Message));
        if (wresp != null)
        {
            wresp.Close();
         
        }
       
    }
 
    wr = null;
    return result; 
 
}
 




呼叫端:


///增加其他參數
NameValueCollection nvc = new NameValueCollection();
nvc.Add("iptDesc", "我是敘述");
 
//上傳檔案
var result = UploadFileByHttpWebRequest("http://192.168.1.100/uploadFile.jsp",
    Server.MapPath("sample3.jpg"), "uploadFileName", "image/jpeg", nvc);
 
//回傳結果
Response.Write(result);


給有需要的人,因為反覆測試花很多時間,順帶一提跟Facebook 很多上傳相片的方法也是透過一樣的方式..


參考文件: http://0rz.tw/5oNBw


當麻許的超技八 2014 | Donma Hsu Design.