java 二进制图片上传_将图片二进制流上传到服务器

该博客详细介绍了如何使用Java调用WebService将图片的二进制流上传到服务器。通过设置请求头、内容类型以及创建multipart/form-data格式的数据,将图片文件与其他参数一起发送到指定的上传服务地址。
摘要由CSDN通过智能技术生成

///

///调用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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值