String end = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
// 定义最后数据分隔线
byte[] end_data = ("\r\n--" + boundary + "--\r\n").getBytes();
try {
URL url = new URL(actionUrl);
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);
/* 设置DataOutputStream */
DataOutputStream out = new DataOutputStream(con.getOutputStream());
StringBuffer params = new StringBuffer();
/*** <-----------------0--------------------> *****/
// username参数 用户名
params.append(twoHyphens + boundary + end);
params.append("Content-Disposition: form-data; name=\"username\"\r\n\r\n");
params.append(configEntity.uname);
params.append("\r\n");
out.write(params.toString().getBytes());// 向服务器发送数据
int leng = imageLists.size();//List
for (int i = 0; i < leng; i++) {//遍历出所有的图片
String fname = imageLists.get(i);
File file = new File(fname);
StringBuilder sb = new StringBuilder();
sb.append(twoHyphens);
sb.append(boundary);
sb.append(end);
sb.append("Content-Disposition: form-data;name=\"img[]\";filename=\""
+ file.getName() + "\"\r\n");
// 这里不能漏掉,根据文件类型来来做处理,由于上传的是图片,所以这里可以写成image/pjpeg
sb.append("Content-Type:image/pjpeg\r\n\r\n");
out.write(sb.toString().getBytes());
DataInputStream in = new DataInputStream(new FileInputStream(
file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
out.write("\r\n".getBytes());
in.close();
}
out.write(end_data);// 向服务器发送数据
out.flush();
out.close();
// 定义BufferedReader输入流来读取URL的响应
BufferedReader reader = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
if (line.matches("topic_ok")) {
handler.sendEmptyMessage(2);
} else {
handler.sendEmptyMessage(3);
}
}
} catch (Exception e) {
handler.sendEmptyMessage(9);
e.printStackTrace();
}