List of usage examples for javax.servlet.http HttpServletRequest getPart
public Part getPart(String name) throws IOException, ServletException;
From source file:algorithm.laddress.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* ww w. j av a 2s.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 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.cirdles.webServices.ambapo.AmbapoServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/* w ww .ja va 2s. c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/csv"); response.setHeader("Content-Disposition", "attachment; filename=converted-file.csv"); String conversionType = ServletRequestUtils.getStringParameter(request, "conversionType", "LatLongtoUTM"); Part filePart = request.getPart("ambapoFile"); String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); InputStream fileStream = filePart.getInputStream(); File myFile = new File(fileName); AmbapoFileHandlerService handler = new AmbapoFileHandlerService(); String fileExt = FilenameUtils.getExtension(fileName); try { File convertedFile = null; if (fileExt.equals("csv")) { convertedFile = handler.convertFile(fileName, fileStream, conversionType).toFile(); response.setContentLengthLong(convertedFile.length()); IOUtils.copy(new FileInputStream(convertedFile), response.getOutputStream()); } else { } } catch (Exception e) { System.err.println(e); } }
From source file:eu.prestoprime.p4gui.ingest.UploadMasterFileServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { User user = Tools.getSessionAttribute(request.getSession(), P4GUI.USER_BEAN_NAME, User.class); RoleManager.checkRequestedRole(USER_ROLE.producer, user.getCurrentP4Service().getRole(), response); // prepare dynamic variables Part masterQualityPart = request.getPart("masterFile"); String targetName = new SimpleDateFormat("yyyyMMdd-HHmm").format(new Date()) + ".mxf"; // prepare static variables String host = "p4.eurixgroup.com"; int port = 21; String username = "pprime"; String password = "pprime09"; FTPClient client = new FTPClient(); try {/*ww w . jav a 2 s. c om*/ client.connect(host, port); if (FTPReply.isPositiveCompletion(client.getReplyCode())) { if (client.login(username, password)) { client.setFileType(FTP.BINARY_FILE_TYPE); // TODO add behavior if file name is already present in // remote ftp folder // now OVERWRITES if (client.storeFile(targetName, masterQualityPart.getInputStream())) { logger.info("Stored file on remote FTP server " + host + ":" + port); request.setAttribute("masterfileName", targetName); } else { logger.error("Unable to store file on remote FTP server"); } } else { logger.error("Unable to login on remote FTP server"); } } else { logger.error("Unable to connect to remote FTP server"); } } catch (IOException e) { e.printStackTrace(); logger.fatal("General exception with FTPClient"); } Tools.servletInclude(this, request, response, "/body/ingest/masterfile/listfiles.jsp"); }
From source file:saludtec.admincloud.web.servicios.ArchivosWeb.java
private JSONArray guardarArchivos(HttpServletRequest r, String idPaciente, String extension, String ruta) throws ServletException, IOException { JSONArray array = new JSONArray(); JSONObject obj = null;// ww w.jav a2 s . c om Integer cantidad = Integer.parseInt(contenidoFormData(r.getPart("cantidad").getInputStream())); Archivo arch = new Archivo(sesion.clinica(r.getSession()).getIdClinica().toString(), idPaciente); for (int i = 0; i < cantidad; i++) { r.getPart("archivo" + i).write(idPaciente + extension); if (arch.crearDirectorioPaciente()) { File archTemp = new File("var/www/AdminCloudData/temp/" + idPaciente + extension); //este rename debe modificarse para que tome el id de la base de datos if (archTemp.renameTo(new File(ruta + idPaciente + extension))) { //aca va el guardado en la base de datos obj = new JSONObject(); obj.put("ruta", arch); array.add(obj); } } else { obj = new JSONObject(); obj.put("error", "no se pudo guardar la imagen"); array.add(obj); } } return array; }
From source file:net.voidfunction.rm.master.AdminServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("Date", HTTPUtils.getServerTime(0)); response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_OK); Part uploadFile = request.getPart("uploadfile"); if (uploadFile == null) throw new ServletException("Uploaded file is null."); // Get some info about the file String filename = getFilename(uploadFile); String contentType = uploadFile.getContentType(); long size = uploadFile.getSize(); byte[] hash = FileUtils.sha256Hash(uploadFile.getInputStream()); // Create a new file object, add it to the database, and store data RMFile newFile = new RMFile(filename, contentType, size, hash); node.getFileRepository().addFile(newFile, uploadFile.getInputStream()); // Output data for interested parties Template tpl = new Template(new File(templateDir + "uploadsuccess.tpl")); tpl.assign("FILENAME", filename); tpl.assign("SIZE", String.valueOf(size)); tpl.assign("TYPE", contentType); tpl.assign("HASH", Hex.encodeHexString(hash)); tpl.assign("FILEID", newFile.getId()); tpl.parse("main"); response.getWriter().print(tpl.out()); // Delete temp file uploadFile.delete();/*from w w w.j ava 2 s . co m*/ // Log node.getLog().info("New file added (via web): " + newFile.getId() + " (" + newFile.getName() + ")"); }
From source file:it.unitn.elisco.servlet.ImageUploadServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from w ww . j ava 2 s. c om*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(false); Person user; if (request.getRequestURI().equals("/admin/image_upload")) { user = (Person) session.getAttribute("admin"); } else { user = (Person) session.getAttribute("student"); } // Get the image uploaded by the user as a stream Part imagePart = request.getPart("image"); String imageExtension = "." + imagePart.getSubmittedFileName().split("\\.")[1]; // Write to a temp file File tempFile = File.createTempFile("tmp", imageExtension); tempFile.deleteOnExit(); FileOutputStream out = new FileOutputStream(tempFile); IOUtils.copy(imagePart.getInputStream(), out); // Upload the image to Cloudinary ImageUploader uploader = ImageUploader.getInstance(); String imageId = uploader.uploadImageToCloud(user, tempFile); // Get the url for the uploaded image String imageUrl = uploader.getURLWithDimensions(imageId, 200, 200); // Send JSON response back to ajax String json = new Gson().toJson(imageUrl); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(json); }
From source file:saludtec.admincloud.web.servicios.ArchivosWeb.java
private JSONArray guardarArchivo(HttpServletRequest r, String idPaciente, String extension, String ruta) throws ServletException, IOException { JSONArray array = new JSONArray(); JSONObject obj = null;//from w w w . j av a 2s.c o m Archivo arch = new Archivo(sesion.clinica(r.getSession()).getIdClinica().toString(), idPaciente); r.getPart("archivo").write(idPaciente + extension); if (arch.crearDirectorioPaciente()) { File archTemp = new File("var/www/AdminCloudData/temp/" + idPaciente + extension); //este rename debe modificarse para que tome el id de la base de datos if (archTemp.renameTo(new File(ruta + idPaciente + extension))) { //aca va el guardado en la base de datos obj = new JSONObject(); obj.put("ruta", arch); array.add(obj); } } else { obj = new JSONObject(); obj.put("error", "no se pudo guardar la imagen"); array.add(obj); } return array; }
From source file:com.sishuok.chapter4.web.servlet.UploadServlet.java
@Override protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { try {/*from w w w . j av a 2s . c o m*/ //servlet?Partnull //9.0.4.v20130625 ?? System.out.println(req.getParameter("name")); //?Part System.out.println("\n\n==========file1"); Part file1Part = req.getPart("file1"); //?? ?Part InputStream file1PartInputStream = file1Part.getInputStream(); System.out.println(IOUtils.toString(file1PartInputStream)); file1PartInputStream.close(); // ?? System.out.println("\n\n==========file2"); Part file2Part = req.getPart("file2"); InputStream file2PartInputStream = file2Part.getInputStream(); System.out.println(IOUtils.toString(file2PartInputStream)); file2PartInputStream.close(); System.out.println("\n\n==========parameter name"); //???? System.out.println(IOUtils.toString(req.getPart("name").getInputStream())); //Part??? jettyparameters?? System.out.println(req.getParameter("name")); //?? ? req.getInputStream(); ?? System.out.println("\n\n=============all part"); for (Part part : req.getParts()) { System.out.println("\n\n=========name:::" + part.getName()); System.out.println("=========size:::" + part.getSize()); System.out.println("=========content-type:::" + part.getContentType()); System.out .println("=========header content-disposition:::" + part.getHeader("content-disposition")); System.out.println("=========file name:::" + getFileName(part)); InputStream partInputStream = part.getInputStream(); System.out.println("=========value:::" + IOUtils.toString(partInputStream)); // partInputStream.close(); // ? ? ? part.delete(); } } catch (IllegalStateException ise) { // ise.printStackTrace(); String errorMsg = ise.getMessage(); if (errorMsg.contains("Request exceeds maxRequestSize")) { //? } else if (errorMsg.contains("Multipart Mime part file1 exceeds max filesize")) { //? ?? } else { // } } }
From source file:net.bluemix.droneselfie.UploadPictureServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); if (id == null) return;//from w ww . ja v a 2 s . co m if (id.equals("")) return; InputStream inputStream = null; Part filePart = request.getPart("my_file"); if (filePart != null) { inputStream = filePart.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); org.apache.commons.io.IOUtils.copy(inputStream, baos); byte[] bytes = baos.toByteArray(); ByteArrayInputStream bistream = new ByteArrayInputStream(bytes); String contentType = "image/png"; java.util.Date date = new java.util.Date(); String uniqueId = String.valueOf(date.getTime()); AttachmentDoc document = new AttachmentDoc(id, AttachmentDoc.TYPE_FULL_PICTURE, date); DatabaseUtilities.getSingleton().getDB().create(document.getId(), document); document = DatabaseUtilities.getSingleton().getDB().get(AttachmentDoc.class, id); AttachmentInputStream ais = new AttachmentInputStream(id, bistream, contentType); DatabaseUtilities.getSingleton().getDB().createAttachment(id, document.getRevision(), ais); javax.websocket.Session ssession; ssession = net.bluemix.droneselfie.SocketEndpoint.currentSession; if (ssession != null) { for (Session session : ssession.getOpenSessions()) { try { if (session.isOpen()) { session.getBasicRemote().sendText("fpic?id=" + id); } } catch (IOException ioe) { ioe.printStackTrace(); } } } String alchemyUrl = ""; String apiKey = ConfigUtilities.getSingleton().getAlchemyAPIKey(); String bluemixAppName = ConfigUtilities.getSingleton().getBluemixAppName(); /* if (bluemixAppName == null) { String host = request.getServerName(); alchemyUrl = "http://access.alchemyapi.com/calls/url/URLGetRankedImageFaceTags?url=http://" + host +"/pic?id=" + id + "&apikey=" + apiKey + "&outputMode=json"; } else { alchemyUrl = "http://access.alchemyapi.com/calls/url/URLGetRankedImageFaceTags?url=http://" + bluemixAppName +".mybluemix.net/pic?id=" + id + "&apikey=" + apiKey + "&outputMode=json"; }*/ alchemyUrl = "http://access.alchemyapi.com/calls/url/URLGetRankedImageFaceTags?url=http://ar-drone-selfie.mybluemix.net/pic?id=" + id + "&apikey=1657f33d25d39ff6d226c5547db6190ea8d5af76&outputMode=json"; System.out.println("alchemyURL: " + alchemyUrl); org.apache.http.client.fluent.Request req = Request.Post(alchemyUrl); org.apache.http.client.fluent.Response res = req.execute(); String output = res.returnContent().asString(); Gson gson = new Gson(); AlchemyResponse alchemyResponse = gson.fromJson(output, AlchemyResponse.class); if (alchemyResponse != null) { List<ImageFace> faces = alchemyResponse.getImageFaces(); if (faces != null) { for (int i = 0; i < faces.size(); i++) { ImageFace face = faces.get(i); String sH = face.getHeight(); String sPX = face.getPositionX(); String sPY = face.getPositionY(); String sW = face.getWidth(); int height = Integer.parseInt(sH); int positionX = Integer.parseInt(sPX); int positionY = Integer.parseInt(sPY); int width = Integer.parseInt(sW); int fullPictureWidth = 640; int fullPictureHeight = 360; positionX = positionX - width / 2; positionY = positionY - height / 2; height = height * 2; width = width * 2; if (positionX < 0) positionX = 0; if (positionY < 0) positionY = 0; if (positionX + width > fullPictureWidth) width = width - (fullPictureWidth - positionX); if (positionY + height > fullPictureHeight) height = height - (fullPictureHeight - positionY); bistream = new ByteArrayInputStream(bytes); javaxt.io.Image image = new javaxt.io.Image(bistream); image.crop(positionX, positionY, width, height); byte[] croppedImage = image.getByteArray(); ByteArrayInputStream bis = new ByteArrayInputStream(croppedImage); date = new java.util.Date(); uniqueId = String.valueOf(date.getTime()); document = new AttachmentDoc(uniqueId, AttachmentDoc.TYPE_PORTRAIT, date); DatabaseUtilities.getSingleton().getDB().create(document.getId(), document); document = DatabaseUtilities.getSingleton().getDB().get(AttachmentDoc.class, uniqueId); ais = new AttachmentInputStream(uniqueId, bis, contentType); DatabaseUtilities.getSingleton().getDB().createAttachment(uniqueId, document.getRevision(), ais); ssession = net.bluemix.droneselfie.SocketEndpoint.currentSession; if (ssession != null) { for (Session session : ssession.getOpenSessions()) { try { if (session.isOpen()) { /* * In addition to portrait url why don't we send a few meta back to client */ ImageTag tag = face.getImageTag(); tag.setUrl("pic?id=" + uniqueId); session.getBasicRemote().sendText(tag.toString()); } } catch (IOException ioe) { ioe.printStackTrace(); } } } } } } } }
From source file:org.geoserver.importer.rest.ImportTaskController.java
public ImportData handleFormPost(HttpServletRequest request) throws IOException, ServletException { String url = IOUtils.toString(request.getPart("url").getInputStream(), encoding); if (url == null) { throw new RestException("Invalid request", HttpStatus.BAD_REQUEST); }/*from ww w. j a va 2s .c om*/ URL location = null; try { location = new URL(url); } catch (MalformedURLException ex) { LOGGER.warning("invalid URL specified in upload : " + url); } // @todo handling remote URL implies asynchronous processing at this stage if (location == null || !location.getProtocol().equalsIgnoreCase("file")) { throw new RestException("Invalid url in request", HttpStatus.BAD_REQUEST); } FileData file; try { file = FileData.createFromFile(new File(location.toURI().getPath())); } catch (Exception ex) { throw new RuntimeException("Unexpected exception", ex); } if (file instanceof Directory) { try { file.prepare(); } catch (IOException ioe) { String msg = "Error processing file: " + file.getFile().getAbsolutePath(); LOGGER.log(Level.WARNING, msg, ioe); throw new RestException(msg, HttpStatus.INTERNAL_SERVER_ERROR); } } return file; }