/// <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