c# 類比提交有附件表格單)

來源:互聯網
上載者:User

最近項目需要,需要在winform中類比表單將資料提交至伺服器,發現單獨提交索引值對很容易實現,單獨實現上傳檔案也很容易實現。要是同時提交索引值對和檔案,比較麻煩。在百度Google了大半天沒有任何收穫。無奈之下,按照 黑月.Net的 的思路去自己寫。經過奮鬥 終於搞定。
方法如下:

public WebResponse SubmitData(string fileName, Uri uri, string[] keys, string[] values)
{
string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(uri);
//httpWebRequest2.Credentials = credentialCache;//
httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary;
httpWebRequest2.Method = "POST";

// Build up the post message header

StringBuilder sb = new StringBuilder();

if (keys != null)
{
for (int i = 0; i < keys.Length; i++)
{
sb.Append("--");
sb.Append(boundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"" + keys[i] + "\"\r\n\r\n");
sb.Append(values[i]);
sb.Append("\r\n");
}
}

sb.Append("--");
sb.Append(boundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"file\"; filename=\"");
sb.Append(Path.GetFileName(fileName));
sb.Append("\"");
sb.Append("\r\n");
sb.Append("Content-Type: application/octet-stream");
sb.Append("\r\n");
sb.Append("\r\n");

string postHeader = sb.ToString();
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);

// Build the trailing boundary string as a byte array
// ensuring the boundary appears on a line by itself
byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
long length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length;
httpWebRequest2.ContentLength = length;

Stream requestStream = httpWebRequest2.GetRequestStream();

// Write out our post header
requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

// Write out the file contents
byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
requestStream.Write(buffer, 0, bytesRead);

// Write out the trailing boundary
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);

WebResponse webResponse2 = httpWebRequest2.GetResponse();
return webResponse2;

}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.