List of usage examples for org.apache.commons.fileupload FileItemStream openStream
InputStream openStream() throws IOException;
From source file:com.cubusmail.gwtui.server.services.AttachmentUploadServlet.java
/** * Create a MimeBodyPart.// www .j a v a2 s . co m * * @param item * @return * @throws MessagingException * @throws IOException */ private DataSource createDataSource(FileItemStream item) throws MessagingException, IOException { final String fileName = FilenameUtils.getName(item.getName()); final String contentType = item.getContentType(); final InputStream stream = item.openStream(); ByteArrayDataSource source = new ByteArrayDataSource(stream, contentType); source.setName(fileName); return source; }
From source file:com.woonoz.proxy.servlet.HttpEntityEnclosingRequestHandler.java
private ContentBody buildContentBodyFromFileItem(FileItemStream fileItem) throws IOException { final String partName = fileItem.getFieldName(); final String contentType = getContentTypeForFileItem(fileItem); return new InputStreamBody(BufferOnCreateInputStream.create(fileItem.openStream()), contentType, partName); }
From source file:Functions.UploadFileServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String houseId = ""; String owner = (String) request.getSession().getAttribute("username"); String url = "/errorPage.jsp"; String message = "fgd"; //System.out.println("houseId= "+houseId); //System.out.println("owner= "+owner); response.setContentType("text/html"); boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { ServletFileUpload upload = new ServletFileUpload(); try {/*from w w w .j a v a2s . co m*/ FileItemIterator itr = upload.getItemIterator(request); while (itr.hasNext()) { FileItemStream item = itr.next(); if (item.isFormField()) { //do something String fieldName = item.getFieldName(); InputStream is = item.openStream(); byte b[] = new byte[is.available()]; is.read(b); String value = new String(b); if ("houseIddd".equals(fieldName)) { houseId = value; } response.getWriter().println(fieldName + ":" + value + "<br/>"); } else { System.out.println("MPHKE STO ELSE GIA NA BALEI SPITIA"); //upload file String path = getServletContext().getRealPath("/"); //String path = getServletContext().getContextPath()+"/"; if (FileUpload.processFile(path, item, houseId, owner)) { System.out.println("MPHKE STO processfile!"); //response.getWriter().println("file uploaded successfully"); message = "file uploaded successfully"; url = "/Estateprofile.jsp?houseId=" + houseId + "&houseOwner=" + owner + "&message=" + message; } else { message = "file uploading failed"; url = "/Estateprofile.jsp?houseId=" + houseId + "&houseOwner=" + owner + "&message=" + message; //response.getWriter().println("file uploading failed"); } } } } catch (FileUploadException ex) { ex.printStackTrace(); //Logger.getLogger(UploadFileServlet.class.getName()).log(Level.SEVERE, null, ex); } RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url); dispatcher.forward(request, response); } }
From source file:in.co.sneh.controller.CargaExcelRural.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* w w w. j a va2s . co 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 { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { CargaExcelReqRural lee = new CargaExcelReqRural(); String Unidad = ""; boolean isMultiPart = ServletFileUpload.isMultipartContent(request); if (isMultiPart) { ServletFileUpload upload = new ServletFileUpload(); try { HttpSession sesion = request.getSession(true); FileItemIterator itr = upload.getItemIterator(request); while (itr.hasNext()) { FileItemStream item = itr.next(); if (item.isFormField()) { String fielName = item.getFieldName(); InputStream is = item.openStream(); byte[] b = new byte[is.available()]; is.read(b); String value = new String(b); response.getWriter().println(fielName + ":" + value + "<br/>"); } else { String path = getServletContext().getRealPath("/"); if (CargaExcelRuralModel.processFile(path, item)) { //response.getWriter().println("file uploaded successfully"); if (lee.obtieneArchivo(path, item.getName())) { out.println("<script>alert('Se carg el Folio Correctamente')</script>"); out.println( "<script>window.location='facturacionRural/cargaRequerimento.jsp'</script>"); } //response.sendRedirect("cargaFotosCensos.jsp"); } else { //response.getWriter().println("file uploading falied"); //response.sendRedirect("cargaFotosCensos.jsp"); } } } } catch (FileUploadException fue) { fue.printStackTrace(); } out.println("<script>alert('No se pudo cargar el Folio, verifique las celdas')</script>"); out.println("<script>window.location='requerimiento.jsp'</script>"); //response.sendRedirect("carga.jsp"); } } finally { out.close(); } }
From source file:cc.vidr.servlet.DatumImportServlet.java
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { try {//from w w w . j a v a 2 s . c o m ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); if (item.isFormField()) continue; String filename = item.getName(); if (filename.isEmpty()) continue; InputStream stream = item.openStream(); resp.getWriter().println("<p>"); try { resp.getWriter().println("Loading '" + filename + "'... "); Program program = new Program(stream); program.parse(); program.assertFacts(Server.factDatabase); program.assertRules(Server.ruleDatabase); resp.getWriter().println("OK"); } catch (RecognitionException e) { resp.getWriter().println("Malformed input: " + e.getMessage()); } catch (UnsafeException e) { resp.getWriter().println("Unsafe rule or non-ground fact encountered: " + e.getMessage()); } catch (IOException e) { resp.getWriter().println("Error opening file: " + e.getMessage()); } resp.getWriter().println("</p>"); } } catch (FileUploadException e) { throw new ServletException(e); } doGet(req, resp); }
From source file:edu.isi.wings.portal.servlets.HandleUpload.java
/** * Handle an HTTP POST request from Plupload. *//* ww w . j a v a2s .c o m*/ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); Config config = new Config(request); if (!config.checkDomain(request, response)) return; Domain dom = config.getDomain(); String name = null; String id = null; String storageDir = dom.getDomainDirectory() + "/"; int chunk = 0; int chunks = 0; boolean isComponent = false; boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter; try { iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); try { InputStream input = item.openStream(); if (item.isFormField()) { String fieldName = item.getFieldName(); String value = Streams.asString(input); if ("name".equals(fieldName)) name = value.replaceAll("[^\\w\\.\\-_]+", "_"); else if ("id".equals(fieldName)) id = value; else if ("type".equals(fieldName)) { if ("data".equals(value)) storageDir += dom.getDataLibrary().getStorageDirectory(); else if ("component".equals(value)) { storageDir += dom.getConcreteComponentLibrary().getStorageDirectory(); isComponent = true; } else { storageDir = System.getProperty("java.io.tmpdir"); } } else if ("chunk".equals(fieldName)) chunk = Integer.parseInt(value); else if ("chunks".equals(fieldName)) chunks = Integer.parseInt(value); } else if (name != null) { File storageDirFile = new File(storageDir); if (!storageDirFile.exists()) storageDirFile.mkdirs(); File uploadFile = new File(storageDirFile.getPath() + "/" + name + ".part"); saveUploadFile(input, uploadFile, chunk); } } catch (Exception e) { this.printError(out, e.getMessage()); e.printStackTrace(); } } } catch (FileUploadException e1) { this.printError(out, e1.getMessage()); e1.printStackTrace(); } } else { this.printError(out, "Not multipart data"); } if (chunks == 0 || chunk == chunks - 1) { // Done upload File partUpload = new File(storageDir + File.separator + name + ".part"); File finalUpload = new File(storageDir + File.separator + name); partUpload.renameTo(finalUpload); String mime = new Tika().detect(finalUpload); if (mime.equals("application/x-sh") || mime.startsWith("text/")) FileUtils.writeLines(finalUpload, FileUtils.readLines(finalUpload)); // Check if this is a zip file and unzip if needed String location = finalUpload.getAbsolutePath(); if (isComponent && mime.equals("application/zip")) { String dirname = new URI(id).getFragment(); location = StorageHandler.unzipFile(finalUpload, dirname, storageDir); finalUpload.delete(); } this.printOk(out, location); } }
From source file:fedora.server.rest.RestUtil.java
/** * Retrieves the contents of the HTTP Request. * @return InputStream from the request//from w w w . jav a 2 s .c om */ public RequestContent getRequestContent(HttpServletRequest request, HttpHeaders headers) throws Exception { RequestContent rContent = null; // See if the request is a multi-part file upload request if (ServletFileUpload.isMultipartContent(request)) { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Parse the request, use the first available File item FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { rContent = new RequestContent(); rContent.contentStream = item.openStream(); rContent.mimeType = item.getContentType(); FileItemHeaders itemHeaders = item.getHeaders(); if (itemHeaders != null) { String contentLength = itemHeaders.getHeader("Content-Length"); if (contentLength != null) { rContent.size = Integer.parseInt(contentLength); } } break; } } } else { // If the content stream was not been found as a multipart, // try to use the stream from the request directly if (rContent == null) { if (request.getContentLength() > 0) { rContent = new RequestContent(); rContent.contentStream = request.getInputStream(); rContent.size = request.getContentLength(); } else { String transferEncoding = request.getHeader("Transfer-Encoding"); if (transferEncoding != null && transferEncoding.contains("chunked")) { BufferedInputStream bis = new BufferedInputStream(request.getInputStream()); bis.mark(2); if (bis.read() > 0) { bis.reset(); rContent = new RequestContent(); rContent.contentStream = bis; } } } } } // Attempt to set the mime type and size if not already set if (rContent != null) { if (rContent.mimeType == null) { MediaType mediaType = headers.getMediaType(); if (mediaType != null) { rContent.mimeType = mediaType.toString(); } } if (rContent.size == 0) { List<String> lengthHeaders = headers.getRequestHeader("Content-Length"); if (lengthHeaders != null && lengthHeaders.size() > 0) { rContent.size = Integer.parseInt(lengthHeaders.get(0)); } } } return rContent; }
From source file:com.google.appinventor.server.GalleryServlet.java
private InputStream getRequestStream(HttpServletRequest req, String expectedFieldName) throws Exception { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); // LOG.info(item.getContentType()); if (item.getFieldName().equals(expectedFieldName)) { return item.openStream(); }/* ww w. j a v a 2 s . c om*/ } throw new IllegalArgumentException("Field " + expectedFieldName + " not found in upload"); }
From source file:com.pronoiahealth.olhie.server.rest.BookAssetUploadServiceImpl.java
/** * Receive an upload book assest/*ww w. ja v a2s.c o m*/ * * @see com.pronoiahealth.olhie.server.rest.BookAssetUploadService#process2(javax.servlet.http.HttpServletRequest) */ @Override @POST @Path("/upload2") @Produces("text/html") @SecureAccess({ SecurityRoleEnum.ADMIN, SecurityRoleEnum.AUTHOR }) public String process2(@Context HttpServletRequest req) throws ServletException, IOException, FileUploadException { try { // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (isMultipart == true) { // FileItemFactory fileItemFactory = new FileItemFactory(); String description = null; String descriptionDetail = null; String hoursOfWorkStr = null; String bookId = null; String action = null; String dataType = null; String contentType = null; //String data = null; byte[] bytes = null; String fileName = null; long size = 0; ServletFileUpload fileUpload = new ServletFileUpload(); fileUpload.setSizeMax(FILE_SIZE_LIMIT); FileItemIterator iter = fileUpload.getItemIterator(req); while (iter.hasNext()) { FileItemStream item = iter.next(); InputStream stream = item.openStream(); if (item.isFormField()) { // description if (item.getFieldName().equals("description")) { description = Streams.asString(stream); } // detail if (item.getFieldName().equals("descriptionDetail")) { descriptionDetail = Streams.asString(stream); } // Work hours if (item.getFieldName().equals("hoursOfWork")) { hoursOfWorkStr = Streams.asString(stream); } // BookId if (item.getFieldName().equals("bookId")) { bookId = Streams.asString(stream); } // action if (item.getFieldName().equals("action")) { action = Streams.asString(stream); } // datatype if (item.getFieldName().equals("dataType")) { dataType = Streams.asString(stream); } } else { if (item != null) { contentType = item.getContentType(); fileName = item.getName(); item.openStream(); InputStream in = item.openStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(in, bos); bytes = bos.toByteArray(); size = bytes.length; } } } // convert the hoursOfWork int hoursOfWork = 0; if (hoursOfWorkStr != null) { try { hoursOfWork = Integer.parseInt(hoursOfWorkStr); } catch (Exception e) { log.log(Level.WARNING, "Could not conver " + hoursOfWorkStr + " to an int in BookAssetUploadServiceImpl. Converting to 0."); hoursOfWork = 0; } } // Verify that the session user is the author or co-author of // the book. They would be the only ones who could add to the // book. String userId = userToken.getUserId(); boolean isAuthor = bookDAO.isUserAuthorOrCoauthorOfBook(userId, bookId); if (isAuthor == false) { throw new Exception("The user " + userId + " is not the author or co-author of the book."); } // Add to the database bookDAO.addUpdateBookassetBytes(description, descriptionDetail, bookId, contentType, BookAssetDataType.valueOf(dataType).toString(), bytes, action, fileName, null, null, size, hoursOfWork, userId); // Tell Solr about the update queueBookEvent.fire(new QueueBookEvent(bookId, userId)); } return "OK"; } catch (Exception e) { log.log(Level.SEVERE, "Throwing servlet exception for unhandled exception", e); // return "ERROR:\n" + e.getMessage(); if (e instanceof FileUploadException) { throw (FileUploadException) e; } else { throw new FileUploadException(e.getMessage()); } } }
From source file:guru.nidi.ramltester.util.FormDecoder.java
private Object valueOf(FileItemStream itemStream) throws IOException { if (itemStream.isFormField()) { final String charset = charset(itemStream.getContentType()); return IoUtils.readIntoString(new InputStreamReader(itemStream.openStream(), charset)); }/*from w w w .j a va 2s . c om*/ return new FileValue(); }