应用程序中向web服务post多文件和post参数
public static string UploadFileEx( string url,
System.Web.HttpFileCollection files, NameValueCollection querystring
)
{
string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
webrequest.Method = "POST";
List<FileInfo_Stream> fileStream = null;
if (files.Count > 0)
{
fileStream = new List<FileInfo_Stream>();
foreach (var file in files.Keys)
{
StringBuilder sb = new StringBuilder();
sb.Append("--");
sb.Append(boundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append(file.ToString());
sb.Append("\"; filename=\"");
sb.Append(files[file.ToString()].FileName);
sb.Append("\"");
sb.Append("\r\n");
sb.Append("Content-Type: ");
sb.Append(files[file.ToString()].ContentType);
sb.Append("\r\n");
sb.Append("\r\n");
FileInfo_Stream fs=new FileInfo_Stream();
fs.postHeaderBytes=Encoding.UTF8.GetBytes(sb.ToString());
fs.stream=files[file.ToString()].InputStream;
fileStream.Add(fs);
}
}
StringBuilder sb1 = new StringBuilder();
foreach (var key in querystring.Keys)
{
sb1.Append("--");
sb1.Append(boundary);
sb1.Append("\r\n");
sb1.Append("Content-Disposition: form-data; name=\""+key.ToString()+"\"");
sb1.Append("\r\n");
sb1.Append("\r\n");
sb1.Append(querystring[key.ToString()].ToString());
sb1.Append("\r\n");
}
//byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sb.ToString());
byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
byte[] postDate = Encoding.UTF8.GetBytes(sb1.ToString());
long length = fileStream.Sum(s1=>s1.postHeaderBytes.Length) +fileStream.Sum(s2=>s2.stream.Length)+ (boundaryBytes.Length * fileStream.Count) + postDate.Length;
webrequest.ContentLength = length;
Stream requestStream = webrequest.GetRequestStream();
requestStream.Write(postDate, 0, postDate.Length);
foreach (var fs in fileStream)
{
requestStream.Write(fs.postHeaderBytes, 0, fs.postHeaderBytes.Length);
byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fs.stream.Length))];
int bytesRead = 0;
while ((bytesRead = fs.stream.Read(buffer, 0, buffer.Length)) != 0)
requestStream.Write(buffer, 0, bytesRead);
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
}
webrequest.Timeout = 1000000;
WebResponse responce = webrequest.GetResponse();
Stream s = responce.GetResponseStream();
StreamReader sr = new StreamReader(s);
string str = sr.ReadToEnd();
foreach (var filestream1 in fileStream)
{
filestream1.stream.Close();
}
requestStream.Close();
sr.Close();
s.Close();
responce.Close();
return str;
}
}
public class FileInfo_Stream
{
public Stream stream { get; set; }
public byte[] postHeaderBytes { get; set; }
}
浙公网安备 33010602011771号