List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload getItemIterator
public FileItemIterator getItemIterator(HttpServletRequest request) throws FileUploadException, IOException
From source file:com.woonoz.proxy.servlet.HttpEntityEnclosingRequestHandler.java
private HttpEntity createMultipartEntity(HttpServletRequest request) throws FileUploadException, IOException { DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); MultipartEntity multipartEntity = new MultipartEntity(); FileItemIterator iterator = servletFileUpload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream fileItem = iterator.next(); final String partName = fileItem.getFieldName(); if (fileItem.isFormField()) { multipartEntity.addPart(partName, buildStringBody(fileItem)); } else {/* w w w .j av a2s .co m*/ multipartEntity.addPart(partName, buildContentBodyFromFileItem(fileItem)); } } return multipartEntity; }
From source file:edu.morgan.server.UploadFileServlet.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { // Check that we have a file upload request RequestDispatcher rd;//from w w w . j av a 2 s . co m response.setContentType("text/html"); isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { rd = request.getRequestDispatcher("fail.jsp"); rd.forward(request, response); } try { ServletFileUpload upload = new ServletFileUpload(); response.setContentType("text/plain"); FileItemIterator iterator = upload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream stream = item.openStream(); this.read(stream); } rd = request.getRequestDispatcher("success.jsp"); rd.forward(request, response); } catch (Exception ex) { throw new ServletException(ex); } }
From source file:com.woonoz.proxy.servlet.HttpPostRequestHandler.java
private HttpEntity createMultipartEntity(HttpServletRequest request, HttpPost httpPost) throws FileUploadException, IOException { DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); MultipartEntity multipartEntity = new MultipartEntity(); FileItemIterator iterator = servletFileUpload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream fileItem = iterator.next(); final String partName = fileItem.getFieldName(); if (fileItem.isFormField()) { multipartEntity.addPart(partName, buildStringBody(fileItem)); } else {/* w ww. j ava 2 s .co m*/ multipartEntity.addPart(partName, buildContentBodyFromFileItem(fileItem)); } } return multipartEntity; }
From source file:n3phele.backend.RepoProxy.java
@POST @Path("{id}/upload/{bucket}") @Consumes(MediaType.MULTIPART_FORM_DATA) public Response upload(@PathParam("id") Long id, @PathParam("bucket") String bucket, @QueryParam("name") String destination, @QueryParam("expires") long expires, @QueryParam("signature") String signature, @Context HttpServletRequest request) throws NotFoundException { Repository repo = Dao.repository().load(id); if (!checkTemporaryCredential(expires, signature, repo.getCredential().decrypt().getSecret(), bucket + ":" + destination)) { log.severe("Expired temporary authorization"); throw new NotFoundException(); }//from w ww .j a va 2 s .c o m try { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(request); log.info("FileSizeMax =" + upload.getFileSizeMax() + " SizeMax=" + upload.getSizeMax() + " Encoding " + upload.getHeaderEncoding()); while (iterator.hasNext()) { FileItemStream item = iterator.next(); if (item.isFormField()) { log.info("FieldName: " + item.getFieldName() + " value:" + Streams.asString(item.openStream())); } else { InputStream stream = item.openStream(); log.warning("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName() + " content " + item.getContentType()); URI target = CloudStorage.factory().putObject(repo, stream, item.getContentType(), destination); Response.created(target).build(); } } } catch (Exception e) { log.log(Level.WARNING, "Processing error", e); } return Response.status(Status.REQUEST_ENTITY_TOO_LARGE).build(); }
From source file:com.cubusmail.gwtui.server.services.AttachmentUploadServlet.java
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); // Create a new file upload handler if (isMultipart) { ServletFileUpload upload = new ServletFileUpload(); try {/*from w w w.j a va 2s . c o m*/ // Parse the request FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { System.out.println( "Form field " + name + " with value " + Streams.asString(stream) + " detected."); } else { System.out .println("File field " + name + " with file name " + item.getName() + " detected."); DataSource source = createDataSource(item); SessionManager.get().getCurrentComposeMessage().addComposeAttachment(source); } JSONObject jsonResponse = null; try { jsonResponse = new JSONObject(); jsonResponse.put("success", true); jsonResponse.put("error", "Upload successful"); } catch (Exception e) { } Writer w = new OutputStreamWriter(response.getOutputStream()); w.write(jsonResponse.toString()); w.close(); stream.close(); } } catch (Exception ex) { ex.printStackTrace(); } } response.setStatus(HttpServletResponse.SC_OK); }
From source file:com.runwaysdk.web.WebFileUploadServlet.java
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ClientRequestIF clientRequest = (ClientRequestIF) req.getAttribute(ClientConstants.CLIENTREQUEST); // capture the session id boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (!isMultipart) { // TODO Change exception type String msg = "The HTTP Request must contain multipart content."; throw new RuntimeException(msg); }/*from w w w .ja v a2 s.c o m*/ FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(); upload.setFileItemFactory(factory); try { // Parse the request FileItemIterator iter = upload.getItemIterator(req); String fileName = null; String extension = null; InputStream stream = null; String uploadPath = null; while (iter.hasNext()) { FileItemStream item = iter.next(); InputStream input = item.openStream(); if (item.isFormField() && item.getFieldName().equals(WEB_FILE_UPLOAD_PATH_FIELD_NAME)) { uploadPath = Streams.asString(input); } else if (!item.isFormField()) { String fullName = item.getName(); int extensionInd = fullName.lastIndexOf("."); fileName = fullName.substring(0, extensionInd); extension = fullName.substring(extensionInd + 1); stream = input; } } if (stream != null) { clientRequest.newFile(uploadPath, fileName, extension, stream); } } catch (FileUploadException e) { throw new FileWriteExceptionDTO(e.getLocalizedMessage()); } }
From source file:com.vmware.photon.controller.api.frontend.resources.vm.VmIsoAttachResource.java
private Task parseIsoDataFromRequest(HttpServletRequest request, String id) throws InternalException, ExternalException { Task task = null;//w w w.j a va 2 s. c om ServletFileUpload fileUpload = new ServletFileUpload(); List<InputStream> dataStreams = new LinkedList<>(); try { FileItemIterator iterator = fileUpload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); if (item.isFormField()) { logger.warn(String.format("The parameter '%s' is unknown in attach ISO.", item.getFieldName())); } else { InputStream fileStream = item.openStream(); dataStreams.add(fileStream); task = vmFeClient.attachIso(id, fileStream, item.getName()); } } } catch (IOException ex) { throw new IsoUploadException("Iso upload IOException", ex); } catch (FileUploadException ex) { throw new IsoUploadException("Iso upload FileUploadException", ex); } finally { for (InputStream stream : dataStreams) { try { stream.close(); } catch (IOException | NullPointerException ex) { logger.warn("Unexpected exception closing data stream.", ex); } } } if (task == null) { throw new IsoUploadException("There is no iso stream data in the iso upload request."); } return task; }
From source file:fi.jyu.student.jatahama.onlineinquirytool.server.LoadSaveServlet.java
@Override public final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { try {//from w ww. j a v a 2s . com // We always return xhtml in utf-8 response.setContentType("application/xhtml+xml"); response.setCharacterEncoding("utf-8"); // Default filename just in case none is found in form String filename = defaultFilename; // Commons file upload ServletFileUpload upload = new ServletFileUpload(); // Go through upload items FileItemIterator iterator = upload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream stream = item.openStream(); if (item.isFormField()) { // Parse form fields String fieldname = item.getFieldName(); if ("chartFilename".equals(fieldname)) { // Ordering is important in client page! We expect filename BEFORE data. Otherwise filename will be default // See also: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4 // "The parts are sent to the processing agent in the same order the // corresponding controls appear in the document stream." filename = Streams.asString(stream, "utf-8"); } else if ("chartDataXML".equals(fieldname)) { log.info("Doing form bounce"); String filenameAscii = formSafeAscii(filename); String fileNameUtf = formSafeUtfName(filename); String cdh = "attachment; filename=\"" + filenameAscii + "\"; filename*=utf-8''" + fileNameUtf; response.setHeader("Content-Disposition", cdh); ServletOutputStream out = response.getOutputStream(); Streams.copy(stream, out, false); out.flush(); // No more processing needed (prevent BOTH form AND upload from happening) return; } } else { // Handle upload log.info("Doing file bounce"); ServletOutputStream out = response.getOutputStream(); Streams.copy(stream, out, false); out.flush(); // No more processing needed (prevent BOTH form AND upload from happening) return; } } } catch (Exception ex) { throw new ServletException(ex); } }
From source file:fedora.server.management.UploadServlet.java
/** * The servlet entry point. http://host:port/fedora/management/upload *///from w w w .j a v a2 s . c o m @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Context context = ReadOnlyContext.getContext(Constants.HTTP_REQUEST.REST.uri, request); try { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Parse the request, looking for "file" InputStream in = null; FileItemIterator iter = upload.getItemIterator(request); while (in == null && iter.hasNext()) { FileItemStream item = iter.next(); LOG.info("Got next item: isFormField=" + item.isFormField() + " fieldName=" + item.getFieldName()); if (!item.isFormField() && item.getFieldName().equals("file")) { in = item.openStream(); } } if (in == null) { sendResponse(HttpServletResponse.SC_BAD_REQUEST, "No data sent.", response); } else { sendResponse(HttpServletResponse.SC_CREATED, s_management.putTempStream(context, in), response); } } catch (AuthzException ae) { throw RootException.getServletException(ae, request, "Upload", new String[0]); } catch (Exception e) { e.printStackTrace(); sendResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getClass().getName() + ": " + e.getMessage(), response); } }
From source file:com.bristle.javalib.net.http.MultiPartFormDataParamMap.java
/************************************************************************** * Parse the specified HTTP request, initializing the map, and calling * the specified callback (if not null) for each file (if any) in the * streamed HTTP request. //from w w w.j a va 2 s .c o m * *@param request The HTTP request *@param callback The callback class *@throws FileUploadException When the request is badly formed. *@throws IOException When an I/O error occurs reading the request. *@throws Throwable When thrown by the callback. **************************************************************************/ public void parseRequestStream(HttpServletRequest request, FileItemStreamCallBack callback) throws FileUploadException, IOException, Throwable { if (ServletFileUpload.isMultipartContent(request)) { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream fileItemStream = iter.next(); if (fileItemStream.isFormField()) { String strParamName = fileItemStream.getFieldName(); InputStream streamIn = fileItemStream.openStream(); String strParamValue = Streams.asString(streamIn); put(strParamName, strParamValue); // Note: Can't do the following usefully. The Parameter // Map of the HTTP Request is effectively readonly. // This does not report an error, but is a no-op. // request.getParameterMap().put(strParamName, strParamValue); } else { if (callback != null) { callback.fullyProcessAFileItemStream(fileItemStream); } } } } else { putAll(request.getParameterMap()); } }