public static int PostFile(string getUrl, CookieContainer cookieContainer, HttpHeader header, string postdata, byte[] postdatabyte, Stream sm)
{
Stream fileStream;
if (sm != null)
{
fileStream = sm;
}
else
{
fileStream = new MemoryStream(postdatabyte);
}
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls;//https形式需要添加
int returnValue = https://www.cnblogs.com/JustinLau/p/0;
fileStream.Position = 0;
var r = new BinaryReader(fileStream);
string strBoundary = "--"+ DateTime.Now.Ticks.ToString("x");
byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "--\r\n");
//請求頭部資訊
StringBuilder sb = new StringBuilder();
sb.Append("--");
sb.Append(strBoundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"importType\"");
sb.Append("\r\n\r\n1");
sb.Append("\r\n");
sb.Append("--");
sb.Append(strBoundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"file\"; filename=\"1.xls\"");
sb.Append("\r\n");
sb.Append("Content-Type: ");
sb.Append("application/octet-stream");
sb.Append("\r\n\r\n");
string strPostHeader = sb.ToString();
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);
try
{
// 根據uri創建HttpWebRequest物件
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(getUrl));
httpReq.Method = "POST";
//對發送的資料不使用快取
httpReq.AllowWriteStreamBuffering = false;
//設定獲得回應的超時時間(300秒)
httpReq.Timeout = 300000;
//httpReq.ServicePoint.Expect100Continue = false;
httpReq.CookieContainer = cookieContainer;
httpReq.Accept = header.accept;
//httpReq.Headers.Add("Accept-Encoding","gzip, deflate, br");
//httpReq.Headers.Add("TE", "Trailers");
httpReq.UserAgent = header.userAgent;
httpReq.ContentType = "multipart/form-data; boundary=" + strBoundary;
long length = fileStream.Length + postHeaderBytes.Length + boundaryBytes.Length;
long fileLength = fileStream.Length;
httpReq.ContentLength = length;
byte[] buffer = new byte[fileLength];
Stream postStream = httpReq.GetRequestStream();
//發送請求頭部訊息
postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
int size = r.Read(buffer, 0, buffer.Length);
postStream.Write(buffer, 0, size);
//添加尾部的時間戳
postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
postStream.Close();
//獲取服務器端的回應
HttpWebResponse webRespon = (HttpWebResponse)httpReq.GetResponse();
if (webRespon.StatusCode == HttpStatusCode.OK) //如果服務器未回應,那么繼續等待相應
{
Stream s = webRespon.GetResponseStream();
StreamReader sr = new StreamReader(s);
//讀取服務器端回傳的訊息
String sReturnString = sr.ReadLine();
s.Close();
sr.Close();
fileStream.Close();
returnValue=https://www.cnblogs.com/JustinLau/p/returnValue;
}
}
catch (Exception ex)
{
UnionLog.WriteLog(LogType.UNION_ERROR, string.Format("匯入Excel失敗:{0}", ex.Message));
}
return returnValue;
}
特別注意:代碼中包括“--”的地方不可以隨意更改,否則踩坑,
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/68930.html
標籤:C#
上一篇:PPT匯出為圖片
下一篇:第1章 類和物件—面向物件概念
