Java Restful web service method to consume MultiPart data throwing exception

I am trying to upload image from android device to server. My Web Service method is getting invoked but it is throwing some exception. I tried searching net for hours but I didn't find any solution to this. I am using multipart for first time. I have changed my web service method.[edited] Here is my android client code

    protected Boolean doInBackground(String... urls) {
          URL urlImage = new URL("");
      HttpURLConnection urlConnectionImage = (HttpURLConnection) urlImage.openConnection();

    ImageButton coverImage = (ImageButton)findViewById(;

     Bitmap bitmap = ((BitmapDrawable)coverImage.getDrawable()).getBitmap();


            urlConnectionImage.setRequestProperty("Connection", "Keep-Alive");
            urlConnectionImage.setRequestProperty("Cache-Control", "no-cache");
           urlConnectionImage.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + this.boundary);
          DataOutputStream request = new DataOutputStream(urlConnectionImage.getOutputStream());

           request.writeBytes(this.twoHyphens + this.boundary + this.crlf);
                        request.writeBytes("Content-Disposition: form-data; name=\"" + this.attachmentName + "\";filename=\"" + this.attachmentFileName + "\"" + this.crlf);
                     /*   byte[] pixels = new byte[bitmap.getWidth() * bitmap.getHeight()];
                        for (int i = 0; i < bitmap.getWidth(); ++i) {
                            for (int j = 0; j < bitmap.getHeight(); ++j) {
                                //we're interested only in the MSB of the first byte,
                                //since the other 3 bytes are identical for B&W images
                                pixels[i + j] = (byte) ((bitmap.getPixel(i, j) & 0x80) >> 7);
 ByteArrayOutputStream bos = new ByteArrayOutputStream();
               bitmap.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
               byte[] bitmapdata = bos.toByteArray();

              // Log.d("pixel size",pixels.clone().toString());
             //   Log.d("real size",Integer.toString(pixels.length));
                        request.writeBytes(this.twoHyphens + this.boundary + this.twoHyphens + this.crlf);
                                            switch (urlConnection.getResponseCode()) {
                            case HttpURLConnection.HTTP_OK:

                               return true;


                                return false; // abort


                        // urlConnection.connect();

                    catch (Exception e)
                        return false;


Here is my web service method[EDITED]. I am getting null value in Buffered Image.

    // @Consumes("multipart/form-data")

     public String retrieveImage(FormDataMultiPart multipart)
        Iterator it =  multipart.getFields().keySet().iterator();
        FormDataBodyPart body = multipart.getField("bitmap");
        InputStream ins = ((BodyPartEntity )body.getEntity()).getInputStream();
        String uploadedFileLocation = "E:\\torr\\A.bmp" ;
        if(ins == null)
            System.out.println("is null");
      // writeToFile(ins, uploadedFileLocation);
        try {

            BufferedImage bi =;
                System.out.println("bi is null");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("exec is "+e);
    //  System.out.println(multipart.getFields().keySet().iterator());
        /*try {
              InputStream source = ins;

            //BufferedImage bi = ImageIO.(source);
              BufferedImage bi =;
             File file = new File("E:\\aditya.bmp");
             if (file.isDirectory()) {
                    ImageIO.write(bi, "bmp", file);
                  } else {
                    ImageIO.write(bi, "bmp", file);

        } catch (IOException e) {
            // TODO Auto-generated catch block

         System.out.println("in retrieveImage"+ multipart.getBodyParts());
         return null;

I have corrected my code. Now it is working. Bitmap was not getting created properly in android doInBackground Method.


You can use FormDataMultiPart

public Response uploadFile(FormDataMultiPart multiPart){
     FormDataBodyPart body = multiPart.getField(<your fieldname>);
     InputStream ins = ((BodyPartEntity) body.getEntity()).getInputStream();
     return Response.status(200).entity(output).build();


Please check your field name "file" is really coming in the multipart otherwise loop through multiPart and get all the field names using


You have to use multipart dependencies


Use uploadFile method something like this:

public Response uploadFile(
        @DefaultValue("true") @FormDataParam("enabled") boolean enabled,
        @FormDataParam("file") InputStream uploadedInputStream,
        @FormDataParam("file") FormDataContentDisposition fileDetail)
//Your code

here logic is making FormDataParam set to true.

Here is one my answer with server as well as client code, might be of your help

File Upload with Jax RS

Check in Eclipse whether Dynamic web Module version is 2.5 or 3.0. I think multipart works only in 3.0 or higher. Please let me know what is the version.

Need Your Help

Why does contentEditable element reject the Enter key?

html keypress contenteditable keydown

I'm using an application that embeds IE control to show content. I change that content to contain a &lt;div contentEditable="True"&gt;Hello World&lt;/div&gt; element. This works well and I can edit...

Using iphone-exif for EXIF data

iphone objective-c exif libexif

I want to use iphone-exif library for EXIF data in my proj. But i dont know if i done any mistake or not it gives error like