【问题标题】:Android send image with httpPost to a Servlet multipartAndroid 将带有 httpPost 的图像发送到 Servlet 多部分
【发布时间】:2012-07-24 07:53:49
【问题描述】:

我尝试使用 multipart 发送图像,就像我在这里读到的 https://stackoverflow.com/a/2937140/1552648 但当它到达 servlet 时它不需要任何东西。

这是 android java 代码,我在其中发送一些文本和图像,我有来自 de SD 卡的 IMG_URL

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());
    }
}

那么,这里也是带有 multipart 的 servlet。

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

@MultipartConfig(location="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);

服务器的日志也说它可以发出请求,因为它发送的不是多部分

提前致谢。

【问题讨论】:

    标签: android jakarta-ee servlets multipart servlet-3.0


    【解决方案1】:

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

        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();
            }
        }
    }
    

    服务器通讯:

        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());
        }
    }
    

    【讨论】:

    • 您发布了与我发布的相同的代码,我的麻烦在于没有发出请求的 servlet。谢谢。
    猜你喜欢
    • 2011-05-02
    • 2016-08-02
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    相关资源
    最近更新 更多