c# 模拟流程器上传附件

/// <summary>
/// 模拟浏览器上传文件
/// </summary>
/// <param name="stream">要上传的文件流</param>
/// <param name="uploadApi">上传地址</param>
/// <param name="contentType">文件类型</param>
/// <param name="fileName">文件名称</param>
/// <param name="otherData">页面其他参数</param>
/// <returns></returns>
public string ImitateBrowserFileToService(MemoryStream stream,string uploadApi,string contentType,string fileName,string otherData)
{
try
{
byte[] postDataBytes = stream.ToArray();
//时间戳 
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=file; filename=" + fileName + "");
sb.Append("\r\n");
sb.Append("Content-Type: " + contentType + "");
sb.Append("\r\n");
sb.Append("\r\n");
sb.Append("\r\n");
string strPostHeader = sb.ToString();
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);
//加入其它参数
string apiUrl = uploadApi;
if (!string.IsNullOrWhiteSpace(otherData))
{
apiUrl = apiUrl + "?" + otherData;
}
//byte[] byteArray = Encoding.UTF8.GetBytes(otherData); //转化
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(apiUrl));
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.ProtocolVersion = HttpVersion.Version11;
webRequest.ContentType = "multipart/form-data; boundary=" + strBoundary;
webRequest.ContentLength = postHeaderBytes.Length + postDataBytes.Length + boundaryBytes.Length;
//webRequest.ContentLength = postHeaderBytes.Length + postDataBytes.Length + boundaryBytes.Length+ byteArray.Length;
webRequest.Timeout = 10000;
using (Stream requestStream = webRequest.GetRequestStream())
{
//requestStream.Write(byteArray, 0, byteArray.Length);
requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
requestStream.Close();
}
WebResponse resp = webRequest.GetResponse();
//读取服务器端返回的消息 
StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
string data = sr.ReadToEnd();
sr.Close();
resp.Close();
return data;
}
catch (Exception ex)
{
throw ex;
}
}

转载于:https://www.cnblogs.com/fengyijun/p/10711371.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值