这个是查看网上的资料及android sdk 开发范例书上的例子之后做出来的,基本上是粘过来的,只是添加了几句代码。下面是代码:
public static String uploadBitmap1(String urlString,byte[] imageBytes){
String endString = "/r/n";
String twoHyphen = "--";
String boundary = "*****";
try {
URL url = new URL(urlString);
final HttpURLConnection con = (HttpURLConnection)url.openConnection();
//允许input、Output,不使用Cache
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
//设置传送的method=POST
con.setRequestMethod("POST");
//setRequestProperty
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
//从主机读取数据的超时时间(单位:毫秒)
con.setReadTimeout(50000);
//设置连接主机的超时时间(单位:毫秒)
con.setConnectTimeout(50000);
//System.out.println(con.getResponseCode());
//设置DataOutputStream
DataOutputStream dsDataOutputStream = new DataOutputStream(con.getOutputStream());
dsDataOutputStream.writeBytes(twoHyphen + boundary + endString);
dsDataOutputStream.writeBytes("Content-Disposition:form-data;" + "name=/"file1/";filename=/"" +
"11.jpg/"" + endString);
dsDataOutputStream.writeBytes(endString);
dsDataOutputStream.write(imageBytes,0,imageBytes.length);
dsDataOutputStream.writeBytes(endString);
dsDataOutputStream.writeBytes(twoHyphen + boundary + twoHyphen + endString);
dsDataOutputStream.close();
int cah = con.getResponseCode();
if(cah == 200){
InputStream isInputStream = con.getInputStream();
int ch;
StringBuffer buffer = new StringBuffer();
while((ch = isInputStream.read()) != -1){
buffer.append((char)ch);
}
return buffer.toString();
}else{
return "false";
}
} catch (Exception e) {
e.printStackTrace();
return "false";
}
}
传过来的参数中byte[] imageBytes是将图片或者是要上传的文件转换后得到的byte数组。其他的就不解释了,查看下面几个文章就知道了(网上找到的很不错的文章)。
http://zsnlovewl.javaeye.com/blog/636650
http://student.csdn.net/space.php?uid=46868&do=blog&id=25873
再写一个简单的Bitmap转换成Byte数组的代码:
ByteArrayOutputStream os = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 70, os);
byte[] imgBytes = os.toByteArray();
bm是Bitmap对象。