先说明一下环境:
服务器是java ee 的servlet
客户端是android
客户端的核心代码:需要导入apache-mime4j-0.6和httpmime-4.0两个包。。。
// 上传图片到服务器
HttpPost httpPost = new HttpPost(urlsString);
// 设置传递参数
MultipartEntity reqEntity = new MultipartEntity();
if (!file1.getAbsoluteFile().equals(""))
{
FileBody fileBody = new FileBody(file1);
reqEntity.addPart("pic", fileBody);
}
StringBody type = new StringBody("wish");
reqEntity.addPart("type", type);
if( type.equals("wish") )
{
StringBody temp = new StringBody(iWishID + "");
reqEntity.addPart("temp", temp);
}
else
{
StringBody temp = new StringBody(sUserName);
reqEntity.addPart("temp", temp);
}
httpPost.setEntity(reqEntity);
// 取得默认的HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 取得HttpResponse
HttpResponse httpResponse = httpclient.execute(httpPost);
// HttpStatus.SC_OK表示连接成功
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
// 取得返回的字符串
String strResult = EntityUtils.toString(httpResponse.getEntity());
System.out.println("yes!");
}
else
{
System.out.println("no!");
}
服务器的接收代码(POST):需要commons-io.jar和commons-io.jar第三方包
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
//普通文本信息处理
String paramName = item.getFieldName();
String paramValue = item.getString();
System.out.println(paramName + ":" + paramValue);
} else {
//上传文件信息处理
String fileName = item.getName();
byte[] data = item.get();
String filePath = getServletContext().getRealPath("/files") + "/" + fileName;
FileOutputStream fos = new FileOutputStream(filePath);
fos.write(data);
fos.close();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
response.getWriter().write("UPLOAD_SUCCESS");
}