赞
踩
public static string uploadRequest(Dictionary<string, object> dictParam, List<UploadFile> fileUrl, Encoding encoding, string url, string keyName)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
WebHeaderCollection header = request.Headers;
request.Method = "post";
//定义请求流
Stream myRequestStream = request.GetRequestStream();
string Boundary = "--WebKitFormBoundary39B5a5e2FWoGbphs";
//构造POST请求体
StringBuilder PostContent = new StringBuilder("");
//组成普通参数信息
foreach (KeyValuePair<string, object> item in dictParam)
{
PostContent.Append("--" + Boundary + "\r\n")
.Append("Content-Disposition: form-data; name=\"" + item.Key + "\"" + "\r\n\r\n" + (string)item.Value + "\r\n");
}
byte[] PostContentByte = encoding.GetBytes(PostContent.ToString());
myRequestStream.Write(PostContentByte, 0, PostContentByte.Length);//写入参数
//文件
for (int i = 0; i < fileUrl.Count; i++)
{
//读取文件信息
FileStream fileStream = new FileStream(fileUrl[i].path, FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] bytes = new byte[fileStream.Length];
fileStream.Read(bytes, 0, bytes.Length);
fileStream.Close();
byte[] UpdateFile = bytes;//转换为二进制
//获取文件名称
string filename = "";
filename = Path.GetFileName(fileUrl[i].path);
//处理文件参数信息
StringBuilder FileContent = new StringBuilder();
FileContent.Append("--" + Boundary + "\r\n")
.Append("Content-Disposition:form-data; name=\"" + keyName + "\";filename=\"" + filename + "\"" + "\r\n\r\n");
byte[] FileContentByte = encoding.GetBytes(FileContent.ToString());
request.ContentType = "multipart/form-data;boundary=" + Boundary;
myRequestStream.Write(FileContentByte, 0, FileContentByte.Length);//写入文件信息
myRequestStream.Write(UpdateFile, 0, UpdateFile.Length);//文件写入请求流中
}
byte[] ContentEnd = encoding.GetBytes("\r\n--" + Boundary + "--\r\n");//请求体末尾,后面会用到
myRequestStream.Write(ContentEnd, 0, ContentEnd.Length);//写入结尾
myRequestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encodingth = response.ContentEncoding;
if (encodingth == null || encodingth.Length < 1)
{
encodingth = "UTF-8"; //默认编码,根据需求自己指定
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encodingth));
string retString = reader.ReadToEnd();
return retString;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。