2012-07-25 58 views
0

我试图发送一个图像使用多部分,就像我在这里读到的https://stackoverflow.com/a/2937140/1552648,但是当它到达servlet时它并不需要任何东西。Android发送带有httpPost的图像到一个Servlet多部分

下面是Android的Java代码,在那里我发送一些文字和图像,我有从德SD卡

private void enviarAlServidorConFoto(Incidencia incide, String IMG_URL){ 

    HttpClient httpClient = new DefaultHttpClient(); 

    HttpPost httpPost = new HttpPost(urlservidor + "AnyadirIncidenciaAndroid"); 

    try { 
     //MultipartEntity multiPart = new MultipartEntity(); 
     MultipartEntity multiPart = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 

     multiPart.addPart("usuario", new StringBody(incide.getUsuario())); 
     multiPart.addPart("latitud", new StringBody(incide.getLatitud()+"")); 
     multiPart.addPart("longitud", new StringBody(incide.getLongitud()+"")); 
     multiPart.addPart("descripcion", new StringBody(incide.getDescripcion())); 
     multiPart.addPart("tipo", new StringBody(incide.getTipo())); 
     // YA la pongo desde la web a normal postParametros.add(new BasicNameValuePair("prioridad", value)); 
     multiPart.addPart("foto", new StringBody(incide.getFoto())); 
     //no se pasa el nombre de la foto, puesto que ya lo extraera cuando se mande la foto sola 
     multiPart.addPart("FotoIncidenciaAndroid", new FileBody(new File(IMG_URL))); 

     httpPost.setEntity(multiPart); 
    } catch (UnsupportedEncodingException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 

    try{  
     HttpResponse res = httpClient.execute(httpPost); 
     res.getEntity().getContent().close(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    }catch (IOException e){ 
     e.printStackTrace(); 
     Log.d("EnviadoAweb", e.toString()); 
    } 
} 

的IMG_URL然后,这里是多也该servlet。

@WebServlet(name="AnyadirIncidenciaAndroid", urlPatterns={"/android/AnyadirIncidenciaAndroid"}, loadOnStartup=1) 

@MultipartConfig(位置= “C:\ TEMP”,fileSizeThreshold = 1024 * 1024,maxFileSize为= 1024 * 1024 * 5,maxRequestSize = 1024 * 1024 * 5 * 5) 公共类AnyadirIncidenciaAndroid延伸的HttpServlet {

private static final long serialVersionUID = -6704540377265399620L; 

/** 
* @see HttpServlet#HttpServlet() 
*/ 
public AnyadirIncidenciaAndroid() { 
    super(); 
    // TODO Auto-generated constructor stub 
} 

/** 
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 
*/ 
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    doPost(request, response); 
} 

/** 
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
*/ 
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 

    final String usuario = request.getParameter("usuario"); 

    System.out.println("Usuario recuperado al dar la incidencia desde movil: " + usuario); 

    IncidenciaDAO idao = new IncidenciaDAO(); 
    Timestamp fechaalta = new Timestamp(System.currentTimeMillis()); 
    Timestamp fechafin = null; 
    double latitud = Double.parseDouble(request.getParameter("latitud")); 
    double longitud = Double.parseDouble(request.getParameter("longitud")); 
    String descripcion = request.getParameter("descripcion"); 
    String tipo = request.getParameter("tipo"); 
    String estado = "Nueva"; 
    String prioridad = "Normal"; 
    String empleado = null; //al tratarse de una incidencias nueva, aun no tenemos ningun empleado que la halla resuelto 
    String foto = request.getParameter("foto"); 
    String nombrefoto = null; 

    /* 
    * Si tenemos foto creada en la aplicacion movil, entonces tendremos que guardar el nuevo 
    * nombre de la incidencia, en caso, de no tener foto, pondremos una string vacio, 
    * y pondremos la imagen por defecto de sin imagen. 
    */ 
    Part p1 = request.getPart("FotoIncidenciaAndroid"); 

    if(foto.equalsIgnoreCase("Si")){ 
     try { 
      nombrefoto = idao.RenombrarFoto(); 
      // guardamos la foto con su nombre 
      p1.write(nombrefoto); 
     } catch (SQLException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 
    } 

    try { 
     idao.anyadirIncidenciaMapaWeb(fechaalta, fechafin, latitud, longitud, descripcion, tipo, estado, prioridad, usuario, empleado, foto, nombrefoto); 
    } catch (SQLException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

}

如何我必须做的,从我从德的请求发送给取? 因为这告诉我,变量usuario为空

final String usuario = request.getParameter(“usuario”); System.out.println(“Usuario recuperado al dar la incidencia desde movil:”+ usuario);

而且日志FOMR服务器说,它可以使请求,因为它送它不是一个多

在此先感谢。

回答

0

我使用这些组件在将图像发送到我的服务器:

public static void uploadPhoto(Uri imageUri, Activity activity, String restaurantId, String itemId) throws Exception{ 
    File imageToUpload = convertImageUriToFile (imageUri, activity); 
    executeMultipartPost(imageToUpload.getAbsolutePath(),restaurantId, itemId); 
} 

其中imageUri是完整路径到图像上:

图片转换器:

public static File convertImageUriToFile(Uri imageUri, Activity activity) { 
    Cursor cursor = null; 
    try { 
     String[] proj = { MediaStore.Images.Media.DATA, 
       MediaStore.Images.Media._ID, 
       MediaStore.Images.ImageColumns.ORIENTATION }; 
     cursor = activity.managedQuery(imageUri, proj, // Which columns to 
                 // return 
       null, // WHERE clause; which rows to return (all rows) 
       null, // WHERE clause selection arguments (none) 
       null); // Order-by clause (ascending by name) 
     int file_ColumnIndex = cursor 
       .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
     Log.v("App engine Manager", "File colum index:"+file_ColumnIndex); 
     // int orientation_ColumnIndex = cursor 
     // .getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION); 
     if (cursor.moveToFirst()) { 
      //String orientation = cursor.getString(orientation_ColumnIndex); 
      return new File(cursor.getString(file_ColumnIndex)); 
     } 
     return null; 
    } finally { 
     if (cursor != null) { 
      cursor.close(); 
     } 
    } 
} 

服务器的COM :

public static void executeMultipartPost(String path, String restaurantId, String itemId) throws Exception { 
    try { 

     Bitmap bm = BitmapFactory.decodeFile(path); 
     String URL = "", imageId = ""; 

     URL = "your server's URL to handle multipart data "; 
     ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
     bm.compress(CompressFormat.JPEG, 75, bos); 
     byte[] data = bos.toByteArray(); 
     HttpClient httpClient = new DefaultHttpClient(); 
     HttpPost postRequest = new HttpPost(URL); 
     ByteArrayBody bab = new ByteArrayBody(data, imageId+".jpg"); 
     MultipartEntity reqEntity = new MultipartEntity(
       HttpMultipartMode.BROWSER_COMPATIBLE); 
     reqEntity.addPart("uploaded", bab); 
     reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf")); 
     postRequest.setEntity(reqEntity); 
     HttpResponse response = httpClient.execute(postRequest); 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       response.getEntity().getContent(), "UTF-8")); 
     String sResponse; 
     StringBuilder s = new StringBuilder(); 

     while ((sResponse = reader.readLine()) != null) { 
      s = s.append(sResponse); 
     } 
     System.out.println("Response: " + s); 
    } catch (Exception e) { 
     // handle exception here 
     Log.e(e.getClass().getName(), e.getMessage()); 
    } 
} 
+0

你hav e发布了与我发布的代码相同的代码,麻烦的是没有发出请求的servlet。谢谢。 – user1552648 2012-07-25 21:32:06

相关问题