@Path("/upload") @POST @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_JSON) public Response upload(FormDataMultiPart form){ List<FormDataBodyPart> parts = form.getFields("file"); List<String> result = new ArrayList<String>(); for (FormDataBodyPart part : parts) { FormDataContentDisposition file = part.getFormDataContentDisposition(); InputStream fileInputStream = part.getValueAs(InputStream.class);
String filePath = "/tmp/" + file.getFileName(); // save the file to the server saveFile(fileInputStream, filePath); String output = "File saved to server location using FormDataMultiPart : " + filePath; result.add(output); } return Response.ok(result).build(); }
// save uploaded file to a defined location on the server privatevoidsaveFile(InputStream uploadedInputStream, String serverLocation){ try { OutputStream outputStream = new FileOutputStream(new File(serverLocation)); int read = 0; byte[] bytes = newbyte[1024]; while ((read = uploadedInputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } outputStream.flush(); outputStream.close(); uploadedInputStream.close();