Androidは画像とパラメータ(属性)をサーバにアップロードします
まず環境について説明します.
サーバはjava eeのservletです
クライアントはandroid
クライアントのコアコード:apache-mime 4 j-0.6とhttpmime-4.0の2つのパッケージをインポートする必要があります.の
サーバの受信コード(POST):commons-ioが必要である.JArとcommons-io.JArサードパーティ製パッケージ
サーバはjava eeのservletです
クライアントはandroid
クライアントのコアコード:apache-mime 4 j-0.6とhttpmime-4.0の2つのパッケージをインポートする必要があります.の
//
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");
}