志在指尖
用双手敲打未来

C#模仿POST上传文件协助类 ​

publicstaticintPostFile(stringgetUrl,CookieContainercookieContainer,HttpHeaderheader,stringpostdata,byte[]postdatabyte,Streamsm)
{
StreamfileStream;
if(sm!=null)
{
fileStream=sm;
}
else
{
fileStream=newMemoryStream(postdatabyte);
}
ServicePointManager.SecurityProtocol=SecurityProtocolType.Tls12|SecurityProtocolType.Tls;//https形式需要增加
intreturnValue=0;
fileStream.Position=0;
varr=newBinaryReader(fileStream);
stringstrBoundary=”–“+DateTime.Now.Ticks.ToString(“x”);
byte[]boundaryBytes=Encoding.ASCII.GetBytes(“\r\n–“+strBoundary+”–\r\n”);
//恳求头部信息c#
StringBuildersb=newStringBuilder();
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”);
stringstrPostHeader=sb.ToString();
byte[]postHeaderBytes=Encoding.UTF8.GetBytes(strPostHeader);
try
{
//依据uri创建HttpWebRequest对象
HttpWebRequesthttpReq=(HttpWebRequest)WebRequest.Create(newUri(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;
longlength=fileStream.Length+postHeaderBytes.Length+boundaryBytes.Length;
longfileLength=fileStream.Length;
httpReq.ContentLength=length;
byte[]buffer=newbyte[fileLength];
StreampostStream=httpReq.GetRequestStream();
//发送恳求头部音讯
postStream.Write(postHeaderBytes,0,postHeaderBytes.Length);
intsize=r.Read(buffer,0,buffer.Length);
postStream.Write(buffer,0,size);
//增加尾部的时刻戳
postStream.Write(boundaryBytes,0,boundaryBytes.Length);
postStream.Close();
//获取服务器端的呼应
HttpWebResponsewebRespon=(HttpWebResponse)httpReq.GetResponse();
if(webRespon.StatusCode==HttpStatusCode.OK)//如果服务器未呼应,那么继续等候相应
{
Streams=webRespon.GetResponseStream();
StreamReadersr=newStreamReader(s);
//读取服务器端返回的音讯
StringsReturnString=sr.ReadLine();
s.Close();
sr.Close();
fileStream.Close();
returnValue=returnValue;
}
}
catch(Exceptionex)
{
UnionLog.WriteLog(LogType.UNION_ERROR,string.Format(“导入Excel失利:{0}”,ex.Message));
}
returnreturnValue;
}

未经允许不得转载:IT技术网站 » C#模仿POST上传文件协助类 ​
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

志在指尖 用双手敲打未来

登录/注册IT技术大全

热门IT技术

C#基础入门   SQL server数据库   系统SEO学习教程   WordPress小技巧   WordPress插件   脚本与源码下载