// uplaod api @Override @POST @Path("/upload") @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_XML) @Transactional(propagation = Propagation.NESTED) public Response saveImage(@Context HttpServletRequest request) { String comment = null; // Token tokenObj = (Token) request.getAttribute("token"); // byte[] image = null; InputStream is = null; BufferedOutputStream out = null; String path = null; try { ServletFileUpload servletFileUpload = new ServletFileUpload(); FileItemIterator fileItemIterator = servletFileUpload.getItemIterator(request); while (fileItemIterator.hasNext()) { FileItemStream fileItemStream = fileItemIterator.next(); if ("comment".equals(fileItemStream.getFieldName())) { StringWriter stringWriter = new StringWriter(); IOUtils.copy(fileItemStream.openStream(), stringWriter, "utf-8"); comment = stringWriter.toString(); } else if ("content".equals(fileItemStream.getFieldName())) { path = createPath(); // save image content // path = ("/Users/aoden/Desktop/aaaaaa.jpg"); is = fileItemStream.openStream(); out = new BufferedOutputStream(new FileOutputStream(path)); int data = -1; while ((data = is.read()) != -1) { out.write(data); } } } Token tokenObj = (Token) request.getAttribute("token"); Photo photo = new Photo(); photo.setComment(comment); photo.setPath(path); photo.setUser(tokenObj.getUser()); photoDao.save(photo); return Response.status(500).entity(buildDTO(200, null)).build(); // User user = tokenObj.getUser(); } catch (HibernateException e) { e.printStackTrace(); return Response.status(500).entity(buildDTO(500, null)).build(); } catch (FileUploadException e) { e.printStackTrace(); return Response.status(500).entity(buildDTO(500, null)).build(); } catch (IOException e) { e.printStackTrace(); return Response.status(500).entity(buildDTO(500, null)).build(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return Response.status(500).entity(buildDTO(500, null)).build(); } finally { // close the streams if (is != null) try { is.close(); } catch (IOException e) { e.printStackTrace(); } if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(); } } }