List of usage examples for javax.servlet.http Part getInputStream
public InputStream getInputStream() throws IOException;
From source file:org.apache.servicecomb.demo.jaxrs.server.CodeFirstJaxrs.java
@Path("/upload1") @POST// w w w.j a va 2 s .com @Produces(MediaType.TEXT_PLAIN) public String fileUpload1(@FormParam("file1") Part file1, @FormParam("file2") Part file2) throws IOException { if (file1 == null || file2 == null) { return "null file"; } try (InputStream is1 = file1.getInputStream(); InputStream is2 = file2.getInputStream()) { String content1 = IOUtils.toString(is1); String content2 = IOUtils.toString(is2); return String.format("%s:%s:%s\n" + "%s:%s:%s", file1.getSubmittedFileName(), file1.getContentType(), content1, file2.getSubmittedFileName(), file2.getContentType(), content2); } }
From source file:es.uma.inftel.blog.servlet.PostServlet.java
private void insertarImagen(HttpServletRequest request, Post idPost) throws ServletException, IOException { int numeroFotos, i; numeroFotos = Integer.parseInt(request.getParameter("numFotos")); for (i = 0; i < numeroFotos + 1; i++) { Part filePart = request.getPart("foto-" + i); if (filePart != null) { if (!filePart.getSubmittedFileName().isEmpty()) { Imagen imagen = new Imagen(); InputStream inputStream = filePart.getInputStream(); byte[] foto = IOUtils.toByteArray(inputStream); imagen.setPostId(idPost); imagen.setFoto(foto);// w w w . jav a2 s . c o m imagenFacade.create(imagen); } } } }
From source file:fr.ybonnel.simpleweb4j.MultipartIntegrationTest.java
@Before public void startServer() { resetDefaultValues();//w w w . ja va2 s. c om port = Integer.getInteger("test.http.port", random.nextInt(10000) + 10000); setPort(port); resource(new RestResource<TestUploadImage>("multipart", TestUploadImage.class) { @Override public TestUploadImage getById(String id) throws HttpErrorException { return null; } @Override public List<TestUploadImage> getAll() throws HttpErrorException { return Collections.emptyList(); } @Override public void update(String id, TestUploadImage resource) throws HttpErrorException { resource.id = id; lastCall = resource; } @Override public TestUploadImage create(TestUploadImage resource) throws HttpErrorException { lastCall = resource; return resource; } @Override public Route<TestUploadImage, TestUploadImage> routeCreate() { return new Route<TestUploadImage, TestUploadImage>("multipart", TestUploadImage.class) { @Override public Response<TestUploadImage> handle(TestUploadImage param, RouteParameters routeParams) throws HttpErrorException { return new Response<>(create(param), HttpServletResponse.SC_CREATED); } @Override protected TestUploadImage getRouteParam(HttpServletRequest request) throws IOException { try { Part dataPart = request.getPart("data"); TestUploadImage data = ContentType.GSON .fromJson(new InputStreamReader(dataPart.getInputStream()), getParamType()); Part imagePart = request.getPart("image"); if (null != imagePart) { data.imageName = ((MultiPartInputStreamParser.MultiPart) imagePart) .getContentDispositionFilename(); data.image = IOUtils.toByteArray(imagePart.getInputStream()); } return data; } catch (ServletException e) { e.printStackTrace(); return null; } } }; } @Override public Route<TestUploadImage, Void> routeUpdate() { return new Route<TestUploadImage, Void>("multipart/:id", TestUploadImage.class) { @Override public Response<Void> handle(TestUploadImage param, RouteParameters routeParams) throws HttpErrorException { update(routeParams.getParam("id"), param); return new Response<>(null); } @Override protected TestUploadImage getRouteParam(HttpServletRequest request) throws IOException { try { Part dataPart = request.getPart("data"); InputStreamReader dataReader = new InputStreamReader(dataPart.getInputStream()); TestUploadImage data = ContentType.GSON.fromJson(dataReader, getParamType()); dataReader.close(); Part imagePart = request.getPart("image"); if (null != imagePart) { data.imageName = ((MultiPartInputStreamParser.MultiPart) imagePart) .getContentDispositionFilename(); data.image = IOUtils.toByteArray(imagePart.getInputStream()); } return data; } catch (ServletException e) { e.printStackTrace(); return null; } } }; } @Override public void delete(String id) throws HttpErrorException { } }); start(false); }
From source file:com.izv.controlador.ControladorAndroid.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* www . j a va 2 s. com*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); boolean forward = false; String target, op, action, view; ControlDB bd; target = request.getParameter("target"); op = request.getParameter("op"); action = request.getParameter("action"); if (target.equals("inmobiliaria") && op.equals("insert") && action.equals("op")) { response.setContentType("text/html;charset=UTF-8"); format = new SimpleDateFormat(); format.applyPattern("yyyy-dd-MM"); Calendar cal = Calendar.getInstance(); Date date = cal.getTime(); format.format(date); Inmueble inmueble = new Inmueble(); inmueble.setLocalidad(request.getParameter("localidad")); inmueble.setDireccion(request.getParameter("direccion")); inmueble.setTipo(request.getParameter("tipo")); inmueble.setUsuario(request.getParameter("usuario")); inmueble.setPrecio(request.getParameter("precio")); inmueble.setFechaalta(date); ModeloInmueble.insert(inmueble); Inmueble inm = ModeloInmueble.get(inmueble.getId() + ""); try (PrintWriter out = response.getWriter()) { out.println(inm.getId() + ""); } } else { if (target.equals("inmobiliaria") && op.equals("imagen") && action.equals("op")) { forward = false; boolean error = false; String id = request.getParameter("id"); response.setContentType("text/html;charset=UTF-8"); Calendar calendario = new GregorianCalendar(); Date date = calendario.getTime(); SimpleDateFormat formatoFecha = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss-SSSSS"); String fecha = formatoFecha.format(date); String titulo = "inmueble_" + id + "_" + fecha; Part archivoPost = request.getPart("archivo"); String carpeta = getServletContext().getRealPath("/") + "fotos/"; InputStream input = archivoPost.getInputStream(); try { OutputStream out = new FileOutputStream(carpeta + titulo + ".jpg"); byte[] b = new byte[2048]; int length; while ((length = input.read(b)) != -1) { out.write(b, 0, length); } } catch (Exception e) { error = true; } finally { input.close(); } Fotos fot = new Fotos(); fot.setIdinmueble(Integer.valueOf(id)); fot.setNombre(titulo + ".jpg"); ModeloFoto.insert(fot); try (PrintWriter out = response.getWriter()) { if (error) { out.println("error"); } else { out.println("foto subida"); // respuesta json chapucera } } } else { if (target.equals("bar")) { try { bd = new ControlDB(); bd.cargarDriver(); bd.conectar(); response.setContentType("application/json"); /* int r = bd.ejecutarDelete("delete from pedidos where idPedido=52"); System.out.println(r); */ // String fechaHora = getFecha(); // String consulta = "insert into pedidos values(0, '" + fechaHora + "', 0, 0, null, 'admin ', 6, 1)"; // bd.ejecutarInsert(consulta); ResultSet r = bd.ejecutarSelect("Select * from pedidos"); JSONArray array = new JSONArray(); ResultSetMetaData rsMetaData = r.getMetaData(); int columns = rsMetaData.getColumnCount(); try { while (r.next()) { JSONObject objetoJSON = new JSONObject(); for (int i = 1; i <= columns; i++) { objetoJSON.put(rsMetaData.getColumnLabel(i), r.getString(i)); } System.out.println(objetoJSON + "\n"); // System.out.println(r.getString(1) + " " + r.getString(2) + " " + r.getString(3) // + " " + r.getString(4)); array.put(objetoJSON); } } catch (SQLException ex) { Logger.getLogger(ControladorAndroid.class.getName()).log(Level.SEVERE, null, ex); } PrintWriter out = response.getWriter(); out.print(array); out.flush(); // obj.put("nombre", "Angel"); // obj.put("password", "1234"); // System.out.println("JSON " + obj.toString()); // System.out.println(obj.getString("nombre") + " " + obj.getString("password")); } catch (JSONException ex) { Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(ControladorAndroid.class.getName()).log(Level.SEVERE, null, ex); } } } } }
From source file:algorithm.laddress.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// ww w . j a v a2s . c om * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); // Create path components to save the file final String path = "C:\\Users\\Rads\\Documents\\NetBeansProjects\\capstone\\src\\java\\algorithm\\"; final Part filePart = request.getPart("file"); final String fileName = getFileName(filePart); OutputStream out = null; InputStream filecontent = null; final PrintWriter writer = response.getWriter(); try { out = new FileOutputStream(new File(path + File.separator + fileName)); filecontent = filePart.getInputStream(); int read = 0; final byte[] bytes = new byte[1024]; while ((read = filecontent.read(bytes)) != -1) { out.write(bytes, 0, read); } // writer.println("New file " + fileName + " created at " + path); LOGGER.log(Level.INFO, "File{0}being uploaded to {1}", new Object[] { fileName, path }); } catch (FileNotFoundException fne) { writer.println("You either did not specify a file to upload or are " + "trying to upload a file to a protected or nonexistent " + "location."); writer.println("<br/> ERROR: " + fne.getMessage()); LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}", new Object[] { fne.getMessage() }); } Scanner s = null; String listOfAddresses = ""; try { String address = fileName; String dname = "C:\\Users\\Rads\\Documents\\NetBeansProjects\\capstone\\src\\java\\algorithm\\" + address; File f = new File(dname); s = new Scanner(f); //s.useDelimiter(","); //Use the normal expression and exclude data we imagine they are not "WORDS" } catch (FileNotFoundException e) { } while (s.hasNextLine()) { String[] curr = s.nextLine().split(","); listOfAddresses = listOfAddresses + "<br/>" + curr[1]; } String nextView = "user.jsp"; request.setAttribute("Address", listOfAddresses); RequestDispatcher view = request.getRequestDispatcher(nextView); view.forward(request, response); }
From source file:org.mhi.servlets.ImageUpload.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); // Service Class for DB - Actions ServiceQuery query = new ServiceQuery(); ServiceUpdate update = new ServiceUpdate(); String imgName = request.getParameter("name"); String imgDesc = request.getParameter("desc"); String imgCat = request.getParameter("category"); String fileSize = null;// w w w.j a va2 s. c o m String fileName = null; String contentType = null; String[] parts = null; InputStream inputStream = null; // input stream of the upload file // obtains the upload file part in this multipart request Part filePart = request.getPart("files"); if (filePart != null) { // Fill up Information extract from File fileSize = "" + filePart.getSize(); parts = filePart.getSubmittedFileName().split("\\."); contentType = filePart.getContentType(); // obtains input stream of the upload file inputStream = filePart.getInputStream(); // new Image Images img = new Images(); // Set Parameters img.setFileName(imgName + "." + parts[1]); img.setName(imgName); img.setDescription(imgDesc); img.setFileBlob(IOUtils.toByteArray(inputStream)); img.setFileSize(fileSize); img.setcTyp(contentType); // Relationship to Category ImgCat cat = query.getCategoryByID(Long.valueOf(imgCat)); img.setCategory(cat); // Persist to Database update.insertImage(img); } response.sendRedirect(request.getServletContext().getContextPath() + "/admin/upload"); }
From source file:org.fejoa.server.Portal.java
@Override public void handle(String s, Request request, HttpServletRequest httpServletRequest, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/plain;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); request.setHandled(true);/* w w w. j a v a 2 s . c om*/ final MultipartConfigElement MULTI_PART_CONFIG = new MultipartConfigElement( System.getProperty("java.io.tmpdir")); if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data")) { request.setAttribute(Request.__MULTIPART_CONFIG_ELEMENT, MULTI_PART_CONFIG); } Session session = new Session(baseDir, httpServletRequest.getSession()); ResponseHandler responseHandler = new ResponseHandler(response); Part messagePart = request.getPart(HTMLRequest.MESSAGE_KEY); Part data = request.getPart(HTMLRequest.DATA_KEY); if (messagePart == null) { responseHandler.setResponseHeader("empty request!"); responseHandler.finish(); return; } StringWriter stringWriter = new StringWriter(); StreamHelper.copy(messagePart.getInputStream(), stringWriter); String error = handleJson(responseHandler, stringWriter.toString(), (data != null) ? data.getInputStream() : null, session); if (!responseHandler.isHandled() || error != null) responseHandler.setResponseHeader(error); responseHandler.finish(); }
From source file:com.izv.controlador.Controlador.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w ww. j av a2 s .c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String destino = "index.html"; boolean forward = false; String target, op, action, view; target = request.getParameter("target"); op = request.getParameter("op"); action = request.getParameter("action"); if (target.equals("inmobiliaria") && op.equals("select") && action.equals("view")) { forward = true; destino = "WEB-INF/inmobiliaria/index.jsp"; request.setAttribute("datos", ModeloInmueble.get()); } else { if (target.equals("inmobiliaria") && op.equals("delete") && action.equals("op")) { forward = false; ModeloInmueble.delete(request.getParameter("id")); destino = "control?target=inmobiliaria&op=select&action=view"; } else { if (target.equals("inmobiliaria") && op.equals("insert") && action.equals("view")) { forward = true; destino = "WEB-INF/inmobiliaria/insert.jsp"; } else { if (target.equals("inmobiliaria") && op.equals("insert") && action.equals("op")) { forward = false; destino = "control?target=inmobiliaria&op=select&action=view"; format = new SimpleDateFormat(); format.applyPattern("yyyy-dd-MM"); Calendar cal = Calendar.getInstance(); Date date = cal.getTime(); format.format(date); Inmueble inmueble = new Inmueble(); inmueble.setLocalidad(request.getParameter("localidad")); inmueble.setDireccion(request.getParameter("direccion")); inmueble.setTipo(request.getParameter("tipo")); inmueble.setUsuario(request.getParameter("usuario")); inmueble.setPrecio(request.getParameter("precio")); inmueble.setFechaalta(date); ModeloInmueble.insert(inmueble); } else { if (target.equals("inmobiliaria") && op.equals("edit") && action.equals("view")) { forward = true; request.setAttribute("inmueble", ModeloInmueble.get(request.getParameter("id"))); destino = "WEB-INF/inmobiliaria/edit.jsp"; } else { if (target.equals("inmobiliaria") && op.equals("edit") && action.equals("op")) { forward = false; destino = "control?target=inmobiliaria&op=select&action=view"; Inmueble inmueble = new Inmueble(); inmueble.setLocalidad(request.getParameter("localidad")); inmueble.setDireccion(request.getParameter("direccion")); inmueble.setTipo(request.getParameter("tipo")); inmueble.setUsuario(request.getParameter("usuario")); inmueble.setId(Integer.parseInt(request.getParameter("id"))); inmueble.setPrecio(request.getParameter("precio")); String fecha = request.getParameter("fecha"); format = new SimpleDateFormat(); format.applyPattern("yyyy-dd-MM"); Date date = null; try { date = format.parse(fecha); } catch (ParseException ex) { Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex); } inmueble.setFechaalta(date); //String id=request.getParameter("id"); ModeloInmueble.update(inmueble); } else { if (target.equals("inmobiliaria") && op.equals("imagen") && action.equals("view")) { forward = true; request.setAttribute("inmueble", ModeloInmueble.get(request.getParameter("id"))); destino = "WEB-INF/inmobiliaria/addImagen.jsp"; } else { if (target.equals("inmobiliaria") && op.equals("imagen") && action.equals("op")) { forward = false; boolean error = false; String id = request.getParameter("id"); response.setContentType("text/html;charset=UTF-8"); Calendar calendario = new GregorianCalendar(); Date date = calendario.getTime(); SimpleDateFormat formatoFecha = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss"); String fecha = formatoFecha.format(date); String titulo = "inmueble_" + id + "_" + fecha; Part archivoPost = request.getPart("archivo"); String carpeta = getServletContext().getRealPath("/") + "fotos/"; InputStream input = archivoPost.getInputStream(); try { OutputStream out = new FileOutputStream(carpeta + titulo + ".jpg"); byte[] b = new byte[2048]; int length; while ((length = input.read(b)) != -1) { out.write(b, 0, length); } } catch (Exception e) { error = true; } finally { input.close(); } Fotos fot = new Fotos(); fot.setIdinmueble(Integer.valueOf(id)); fot.setNombre(titulo + ".jpg"); ModeloFoto.insert(fot); destino = "control?target=inmobiliaria&op=select&action=view"; } else { if (target.equals("inmobiliaria") && op.equals("imagenes") && action.equals("view")) { forward = true; request.setAttribute("inmueble", ModeloInmueble.get(request.getParameter("id"))); destino = "WEB-INF/inmobiliaria/imageview.jsp"; } else { if (target.equals("inmobiliaria") && op.equals("deletefoto") && action.equals("op")) { forward = false; ModeloFoto.delete(request.getParameter("id")); destino = "control?target=inmobiliaria&op=select&action=view"; } } } } } } } } } } if (forward) { request.getRequestDispatcher(destino).forward(request, response); } else { response.sendRedirect(destino); } }
From source file:org.apache.servicecomb.foundation.vertx.http.TestVertxServerResponseToHttpServletResponse.java
@Test public void sendPart_succ(@Mocked Part part, @Mocked InputStream inputStream) throws IOException, InterruptedException, ExecutionException { new Expectations() { {//from w w w . j a v a 2 s .co m part.getInputStream(); result = inputStream; inputStream.read((byte[]) any); result = -1; } }; CompletableFuture<Void> future = response.sendPart(part); Assert.assertNull(future.get()); }
From source file:org.apache.servicecomb.demo.springmvc.server.CodeFirstSpringmvc.java
private String _fileUpload(MultipartFile file1, Part file2) { try (InputStream is1 = file1.getInputStream(); InputStream is2 = file2.getInputStream()) { String content1 = IOUtils.toString(is1); String content2 = IOUtils.toString(is2); return String.format("%s:%s:%s\n" + "%s:%s:%s", file1.getOriginalFilename(), file1.getContentType(), content1, file2.getSubmittedFileName(), file2.getContentType(), content2); } catch (IOException e) { throw new IllegalArgumentException(e); }//w ww. jav a2 s.c om }