首先写好一个专门用于封装提交的信息的处理类
FormFile.java
package com.cnjmwl.util;
public class FormFile
{
/* 上传文件的数据 */
private byte[] data;
/* 文件名称 */
private String filname;
/* 表单字段名称*/
private String formname;
/* 内容类型 */
private String contentType = "text/plain"; //需要查阅相关的资料
public FormFile(String filname, byte[] data, String formname, String contentType) {
this.data = data;
this.filname = filname;
this.formname = formname;
if(contentType!=null) this.contentType = contentType;
}
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
public String getFilname() {
return filname;
}
public void setFilname(String filname) {
this.filname = filname;
}
public String getFormname() {
return formname;
}
public void setFormname(String formname) {
this.formname = formname;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
}
然后写android客户端提交到的方法
String actionURl="http://192.168.1.79:6888/jmcustomer/placeOrderServlet";
//String actionURl=HttpUtil.BASE_URL+"new";
Map<String, String> params=new HashMap<String, String>();
//传个用户名
params.put("username", this.getIntent().getStringExtra("username"));
params.put("orderdesc", StringUtil.utf8ToUnicode(orderdesc.getText().toString()));
String contentType = "image/JPEG";
File file =new File("/data/data/test.jpg");
byte[] buffer = new byte[1024];
int len = -1;
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
BufferedInputStream bufferedInputStream;
try {
bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
while ((len = bufferedInputStream.read(buffer)) != -1)
{
outStream.write(buffer, 0, len);
}
data = outStream.toByteArray();
outStream.close();
bufferedInputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//获取用户编辑照片的文件名
String photoName=fileName.getText().toString();
if(photoName==null||photoName.trim().equals("")){
photoName="default";
}
// FormFile[] files=new FormFile[]{new FormFile("test.jpg",data,"file1",contentType)};
FormFile[] files=new FormFile[]{new FormFile(photoName+".jpg",mContent,"file1",contentType)};
String result= post(actionURl, params, files);
if(result.equals("1")){
showAlert("提交成功!");
}else{
showAlert("提交失败!");
}
/**
* 直接通过HTTP协议提交数据到服务器,实现表单提交功能
* @param actionUrl 上传路径
* @param params 请求参数 key为参数名,value为参数值
* @param file 上传文件
*/
public static String post(String actionUrl, Map<String, String> params, FormFile[] files) {
try {
String BOUNDARY = "---------7d4a6d158c9"; //数据分隔线
String MULTIPART_FORM_DATA = "multipart/form-data";
URL url = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);//允许输入
conn.setDoOutput(true);//允许输出
conn.setUseCaches(false);//不使用Cache
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY);
StringBuilder sb = new StringBuilder();
//上传的表单参数部分,格式请参考文章
for (Map.Entry<String, String> entry : params.entrySet()) {//构建表单字段内容
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data; name=\""+ entry.getKey() + "\"\r\n\r\n");
sb.append(entry.getValue());
sb.append("\r\n");
}
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(sb.toString().getBytes());//发送表单字段数据
//上传的文件部分,格式请参考文章
for(FormFile file : files){
StringBuilder split = new StringBuilder();
split.append("--");
split.append(BOUNDARY);
split.append("\r\n");
split.append("Content-Disposition: form-data;name=\""+ file.getFormname()+"\";filename=\""+ file.getFilname() + "\"\r\n");
split.append("Content-Type: "+ file.getContentType()+"\r\n\r\n");
outStream.write(split.toString().getBytes());
outStream.write(file.getData(), 0, file.getData().length);
outStream.write("\r\n".getBytes());
}
byte[] end_data = ("--" + BOUNDARY + "--\r\n").getBytes();//数据结束标志
outStream.write(end_data);
outStream.flush();
int cah = conn.getResponseCode();
if (cah != 200) throw new RuntimeException("请求url失败");
InputStream is = conn.getInputStream();
int ch;
StringBuilder b = new StringBuilder();
while( (ch = is.read()) != -1 ){
b.append((char)ch);
}
outStream.close();
conn.disconnect();
return b.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}