///
///调用webservice将图片的二进制流上传到服务器///
/// 上传图片的服务地址
///
/// 文件的二进制流
/// 名称...我这里填"file"就没错了,,,,
/// contentType的值(这里传的是图片类型为:image/jpeg)
/// 键值对,Webservice服务哪里需要的其它数据,比如上传的用户ID及其他信息
///
public static string HttpUploadFile(string url,string file,byte[] pic, string paramName, stringcontentType, NameValueCollection nvc)
{string result = string.Empty;string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest req=(HttpWebRequest)WebRequest.Create(url);
req.ContentType= "multipart/form-data; boundary=" +boundary;
req.Method= "POST";
req.KeepAlive= true;
req.Credentials=System.Net.CredentialCache.DefaultCredentials;
Stream writeStream=req.GetRequestStream();foreach (string key innvc.Keys)
{
writeStream.Write(boundarybytes,0, boundarybytes.Length);//string formitem = string.Format(formdataTemplate, key, nvc[key]);
string formdataTemplate = "Content-Disposition: form-data; name=\"" + key + "\"\r\n\r\n" +nvc[key];byte[] formitembytes =System.Text.Encoding.UTF8.GetBytes(formdataTemplate);
writeStream.Write(formitembytes,0, formitembytes.Length);
}
writeStream.Write(boundarybytes,0, boundarybytes.Length);string headerTemplate = "Content-Disposition: form-data; name=\""+paramName+"\"; filename=\""+file+"\"\r\nContent-Type:"+contentType+"\r\n\r\n";//string header = string.Format(headerTemplate, paramName, file, contentType);
byte[] headerbytes =System.Text.Encoding.UTF8.GetBytes(headerTemplate);
writeStream.Write(headerbytes,0, headerbytes.Length);
writeStream.Write(pic,0, pic.Length);byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
writeStream.Write(trailer,0, trailer.Length);
writeStream.Close();
WebResponse response= null;try{
response=req.GetResponse();using (StreamReader streamReader = newStreamReader(response.GetResponseStream()))
{
result=streamReader.ReadToEnd();
}
}catch(Exception ex)
{
result=ex.Message;
}finally{if (response != null)
{
response.Close();
response= null;
}if (writeStream != null)
{
writeStream.Close();
writeStream= null;
}if(req!=null)
req= null;
}returnresult;
}