简体   繁体   English

Java Restful Web服务方法消耗MultiPart数据抛出异常

[英]Java Restful web service method to consume MultiPart data throwing exception

I am trying to upload image from android device to server. 我正在尝试将图像从android设备上传到服务器。 My Web Service method is getting invoked but it is throwing some exception. 我的Web服务方法正在被调用,但是它引发了一些异常。 I tried searching net for hours but I didn't find any solution to this. 我尝试在网上搜索几个小时,但没有找到任何解决方案。 I am using multipart for first time. 我是第一次使用multipart。 I have changed my web service method.[edited] Here is my android client code 我已经更改了Web服务方法。[编辑]这是我的android客户端代码

    protected Boolean doInBackground(String... urls) {
      try{
          URL urlImage = new URL("http://10.0.2.2:8080/LostLove_services/love/Recipe/coverpic");
      HttpURLConnection urlConnectionImage = (HttpURLConnection) urlImage.openConnection();

    ImageButton coverImage = (ImageButton)findViewById(R.id.CoverPic);

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


             urlConnectionImage.setUseCaches(false);
              urlConnectionImage.setDoOutput(true);
             urlConnectionImage.setDoInput(true);

            urlConnectionImage.setRequestMethod("POST");
            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);
                        request.writeBytes(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.write(bitmapdata);
                                             request.writeBytes(this.crlf);
                        request.writeBytes(this.twoHyphens + this.boundary + this.twoHyphens + this.crlf);
                        request.flush();
                        Log.d("imageout",Integer.toString(urlConnectionImage.getResponseCode()));
                        request.close();
                                            switch (urlConnection.getResponseCode()) {
                            case HttpURLConnection.HTTP_OK:

                               return true;

                            default:

                                return false; // abort

                        }

                        // urlConnection.connect();

                    }
                    catch (Exception e)
                    {
                        Log.d("exeJsonPublish",e.toString());
                        return false;
                    }

                }

Here is my web service method[EDITED]. 这是我的Web服务方法[编辑]。 I am getting null value in Buffered Image. 我在缓冲图像中得到了空值。

   @Path("/coverpic") 
     @POST
    // @Consumes("multipart/form-data")

     public String retrieveImage(FormDataMultiPart multipart)
     {
        Iterator it =  multipart.getFields().keySet().iterator();
        //System.out.println(it.next());
        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 = ImageIO.read(ins);
            if(bi==null)
                System.out.println("bi is null");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
            System.out.println("exec is "+e);
        }
    //  System.out.println(multipart.getFields().keySet().iterator());
        /*try {
              InputStream source = ins;

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

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/



         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. 无法在android doInBackground方法中正确创建位图。

Use uploadFile method something like this: 使用uploadFile方法是这样的:

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. 这里的逻辑是将FormDataParam设置为true。

Here is one my answer with server as well as client code, might be of your help 这是我对服务器以及客户端代码的回答,可能对您有所帮助

File Upload with Jax RS 用Jax RS上传文件

You can use FormDataMultiPart 您可以使用FormDataMultiPart

@POST
@Path("/coverpic")
@Consumes(MediaType.MULTIPART_FORM_DATA)
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 请检查您的字段名称“ file ”是否确实包含在multipart中,否则请遍历multiPart并使用以下命令获取所有字段名称

multiPart.getFields().keySet().iterator()

You have to use multipart dependencies 您必须使用多部分依赖

<dependency>
    <groupId>com.sun.jersey.contribs</groupId>
    <artifactId>jersey-multipart</artifactId>
    <version>1.18.3</version>
</dependency>
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>

Check in Eclipse whether Dynamic web Module version is 2.5 or 3.0. 在Eclipse中检查Dynamic Web Module版本是2.5还是3.0。 I think multipart works only in 3.0 or higher. 我认为multipart仅适用于3.0或更高版本。 Please let me know what is the version. 请让我知道什么版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM