List of usage examples for org.apache.commons.fileupload FileItemIterator next
FileItemStream next() throws FileUploadException, IOException;
From source file:fedora.server.rest.RestUtil.java
/** * Retrieves the contents of the HTTP Request. * @return InputStream from the request/*from w w w . j av a 2 s. c o m*/ */ 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:fi.jyu.student.jatahama.onlineinquirytool.server.LoadSaveServlet.java
@Override public final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { try {/*from w ww . jav a 2 s . c om*/ // 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:br.edu.ifpb.sislivros.model.ProcessadorFotos.java
public String processarArquivo(HttpServletRequest request, String nameToSave) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { ServletFileUpload upload = new ServletFileUpload(); try {/*from ww w . ja v a 2 s .c o m*/ FileItemIterator itr = upload.getItemIterator(request); while (itr.hasNext()) { FileItemStream item = itr.next(); if (!item.isFormField()) { // pode ser tb sem a barra ???? // String path = request.getServletContext().getRealPath(""); String contextPath = request.getServletContext().getRealPath("/"); //refatorar aqui apenas para salvarimagem receber um pasta, inputStream e o nome //aqui, criar um inputStream atravs do arquivo item antes de enviar //diminuir 1 mtodo, deixando salvarImagem mais genrico if (salvarImagem(contextPath + File.separator + folder, item, nameToSave)) { return folder + "/" + nameToSave; } } } } catch (FileUploadException ex) { System.out.println("erro ao obter informaoes sobre o arquivo"); } } else { System.out.println("Erro no formulario!"); } return null; }
From source file:edu.ucla.loni.pipeline.server.Upload.Uploaders.FileUploadServlet.java
/** * Handles Request to Upload File, Builds a Response * /*from w w w. j a v a2 s.co m*/ * @param req * @param respBuilder */ private void handleFileUpload(HttpServletRequest req, ResponseBuilder respBuilder) { // process only multipart requests if (ServletFileUpload.isMultipartContent(req)) { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); try { // Parse the request FileItemIterator iter = upload.getItemIterator(req); while (iter.hasNext()) { FileItemStream item = iter.next(); handleUploadedFile(item, respBuilder); } } catch (FileUploadException e) { respBuilder.appendRespMessage("The file was not uploaded successfully."); } catch (IOException e) { respBuilder.appendRespMessage("The file was not uploaded successfully."); } } else { respBuilder.appendRespMessage("Your form of request is not supported by this upload servlet."); } }
From source file:com.fizzbuzz.vroom.extension.googlecloudstorage.api.resource.GcsFilesResource.java
/** * * @param rep//from ww w . ja va2s. co m */ public void postResource(final Representation rep) { if (rep == null) setStatus(Status.CLIENT_ERROR_BAD_REQUEST); else { try { FileUpload fileUpload = new FileUpload(); FileItemIterator fileItemIterator = fileUpload.getItemIterator(new RepresentationContext(rep)); if (fileItemIterator.hasNext()) { FileItemStream fileItemStream = fileItemIterator.next(); validateFileItemStream(fileItemStream); String fileName = fileItemStream.getName(); byte[] bytes = ByteStreams.toByteArray(fileItemStream.openStream()); F file = createFile(fileName); mBiz.create(file, bytes); // we're not going to send a representation of the file back to the client, since they probably // don't want that. Instead, we'll send them a 201, with the URL to the created file in the // Location header of the response. getResponse().setStatus(Status.SUCCESS_CREATED); // set the Location response header String uri = getElementUri(file); getResponse().setLocationRef(uri); mLogger.info("created new file resource at: {}", uri); } } catch (FileUploadException e) { throw new IllegalArgumentException( "caught FileUploadException while attempting to parse " + "multipart form", e); } catch (IOException e) { throw new IllegalArgumentException( "caught IOException while attempting to parse multipart " + "form", e); } } }
From source file:fi.helsinki.lib.simplerest.CollectionLogoResource.java
@Put public Representation put(Representation logoRepresentation) { Context c = null;// w w w . ja va 2s.com Collection collection; try { c = getAuthenticatedContext(); collection = Collection.find(c, this.collectionId); if (collection == null) { return errorNotFound(c, "Could not find the collection."); } } catch (SQLException e) { return errorInternal(c, e.toString()); } try { RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory()); FileItemIterator iter = rfu.getItemIterator(logoRepresentation); if (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { InputStream inputStream = item.openStream(); collection.setLogo(inputStream); Bitstream logo = collection.getLogo(); BitstreamFormat bf = BitstreamFormat.findByMIMEType(c, item.getContentType()); logo.setFormat(bf); logo.update(); collection.update(); } } c.complete(); } catch (AuthorizeException ae) { return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED); } catch (Exception e) { return errorInternal(c, e.toString()); } return successOk("Logo set."); }
From source file:fi.helsinki.lib.simplerest.CommunityLogoResource.java
@Put public Representation put(Representation logoRepresentation) { Context c = null;// ww w. ja v a2s .c o m Community community; try { c = getAuthenticatedContext(); community = Community.find(c, this.communityId); if (community == null) { return errorNotFound(c, "Could not find the community."); } } catch (SQLException e) { return errorInternal(c, e.toString()); } try { RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory()); FileItemIterator iter = rfu.getItemIterator(logoRepresentation); if (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { InputStream inputStream = item.openStream(); community.setLogo(inputStream); Bitstream logo = community.getLogo(); BitstreamFormat bf = BitstreamFormat.findByMIMEType(c, item.getContentType()); logo.setFormat(bf); logo.update(); community.update(); } } c.complete(); } catch (AuthorizeException ae) { return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED); } catch (Exception e) { return errorInternal(c, e.toString()); } return successOk("Logo set."); }
From source file:com.fullmetalgalaxy.server.pm.PMServlet.java
@Override protected void doPost(HttpServletRequest p_request, HttpServletResponse p_response) throws ServletException, IOException { ServletFileUpload upload = new ServletFileUpload(); try {// www . j av a 2 s. c o m // build message to send Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage msg = new MimeMessage(session); msg.setSubject("[FMG] no subject", "text/plain"); msg.setSender(new InternetAddress("admin@fullmetalgalaxy.com", "FMG Admin")); msg.setFrom(new InternetAddress("admin@fullmetalgalaxy.com", "FMG Admin")); EbAccount fromAccount = null; // Parse the request FileItemIterator iter = upload.getItemIterator(p_request); while (iter.hasNext()) { FileItemStream item = iter.next(); if (item.isFormField()) { if ("msg".equalsIgnoreCase(item.getFieldName())) { msg.setContent(Streams.asString(item.openStream(), "UTF-8"), "text/plain"); } if ("subject".equalsIgnoreCase(item.getFieldName())) { msg.setSubject("[FMG] " + Streams.asString(item.openStream(), "UTF-8"), "text/plain"); } if ("toid".equalsIgnoreCase(item.getFieldName())) { EbAccount account = null; try { account = FmgDataStore.dao().get(EbAccount.class, Long.parseLong(Streams.asString(item.openStream(), "UTF-8"))); } catch (NumberFormatException e) { } if (account != null) { msg.addRecipient(Message.RecipientType.TO, new InternetAddress(account.getEmail(), account.getPseudo())); } } if ("fromid".equalsIgnoreCase(item.getFieldName())) { try { fromAccount = FmgDataStore.dao().get(EbAccount.class, Long.parseLong(Streams.asString(item.openStream(), "UTF-8"))); } catch (NumberFormatException e) { } if (fromAccount != null) { if (fromAccount.getAuthProvider() == AuthProvider.Google && !fromAccount.isHideEmailToPlayer()) { msg.setFrom(new InternetAddress(fromAccount.getEmail(), fromAccount.getPseudo())); } else { msg.setFrom( new InternetAddress(fromAccount.getFmgEmail(), fromAccount.getPseudo())); } } } } } // msg.addRecipients( Message.RecipientType.BCC, InternetAddress.parse( // "archive@fullmetalgalaxy.com" ) ); Transport.send(msg); } catch (Exception e) { log.error(e); p_response.sendRedirect("/genericmsg.jsp?title=Error&text=" + e.getMessage()); return; } p_response.sendRedirect("/genericmsg.jsp?title=Message envoye"); }
From source file:echopoint.tucana.JakartaCommonsFileUploadProvider.java
/** * @see UploadSPI#handleUpload(nextapp.echo.webcontainer.Connection , * FileUploadSelector, String, UploadProgress) *///from ww w . j av a 2 s.c o m @SuppressWarnings({ "ThrowableInstanceNeverThrown" }) public void handleUpload(final Connection conn, final FileUploadSelector uploadSelect, final String uploadIndex, final UploadProgress progress) throws Exception { final ApplicationInstance app = conn.getUserInstance().getApplicationInstance(); final DiskFileItemFactory itemFactory = new DiskFileItemFactory(); itemFactory.setRepository(getDiskCacheLocation()); itemFactory.setSizeThreshold(getMemoryCacheThreshold()); String encoding = conn.getRequest().getCharacterEncoding(); if (encoding == null) { encoding = "UTF-8"; } final ServletFileUpload upload = new ServletFileUpload(itemFactory); upload.setHeaderEncoding(encoding); upload.setProgressListener(new UploadProgressListener(progress)); long sizeLimit = uploadSelect.getUploadSizeLimit(); if (sizeLimit == 0) sizeLimit = getFileUploadSizeLimit(); if (sizeLimit != NO_SIZE_LIMIT) { upload.setSizeMax(sizeLimit); } String fileName = null; String contentType = null; try { final FileItemIterator iter = upload.getItemIterator(conn.getRequest()); if (iter.hasNext()) { final FileItemStream stream = iter.next(); if (!stream.isFormField()) { fileName = FilenameUtils.getName(stream.getName()); contentType = stream.getContentType(); final Set<String> types = uploadSelect.getContentTypeFilter(); if (!types.isEmpty()) { if (!types.contains(contentType)) { app.enqueueTask(uploadSelect.getTaskQueue(), new InvalidContentTypeRunnable( uploadSelect, uploadIndex, fileName, contentType, progress)); return; } } progress.setStatus(Status.inprogress); final FileItem item = itemFactory.createItem(fileName, contentType, false, stream.getName()); item.getOutputStream(); // initialise DiskFileItem internals uploadSelect.notifyCallback( new UploadStartEvent(uploadSelect, uploadIndex, fileName, contentType, item.getSize())); IOUtils.copy(stream.openStream(), item.getOutputStream()); app.enqueueTask(uploadSelect.getTaskQueue(), new FinishRunnable(uploadSelect, uploadIndex, fileName, item, progress)); return; } } app.enqueueTask(uploadSelect.getTaskQueue(), new FailRunnable(uploadSelect, uploadIndex, fileName, contentType, new RuntimeException("No multi-part content!"), progress)); } catch (final FileUploadBase.SizeLimitExceededException e) { app.enqueueTask(uploadSelect.getTaskQueue(), new FailRunnable(uploadSelect, uploadIndex, fileName, contentType, new UploadSizeLimitExceededException(e), progress)); } catch (final FileUploadBase.FileSizeLimitExceededException e) { app.enqueueTask(uploadSelect.getTaskQueue(), new FailRunnable(uploadSelect, uploadIndex, fileName, contentType, new UploadSizeLimitExceededException(e), progress)); } catch (final MultipartStream.MalformedStreamException e) { app.enqueueTask(uploadSelect.getTaskQueue(), new CancelRunnable(uploadSelect, uploadIndex, fileName, contentType, e, progress)); } }
From source file:kg12.Ex12_1.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w . j a va2 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"); PrintWriter out = response.getWriter(); try { out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet Ex12_1</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>???</h1>"); // multipart/form-data ?? if (ServletFileUpload.isMultipartContent(request)) { out.println("???<br>"); } else { out.println("?????<br>"); out.close(); return; } // ServletFileUpload?? DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload sfu = new ServletFileUpload(factory); // ??? int fileSizeMax = 1024000; factory.setSizeThreshold(1024); sfu.setSizeMax(fileSizeMax); sfu.setHeaderEncoding("UTF-8"); // ? String format = "%s:%s<br>%n"; // ??????? FileItemIterator fileIt = sfu.getItemIterator(request); while (fileIt.hasNext()) { FileItemStream item = fileIt.next(); if (item.isFormField()) { // out.print("<br>??<br>"); out.printf(format, "??", item.getFieldName()); InputStream is = item.openStream(); // ? byte ?? byte[] b = new byte[255]; // byte? b ???? is.read(b, 0, b.length); // byte? b ? "UTF-8" ??String??? result ? String result = new String(b, "UTF-8"); out.printf(format, "", result); } else { // out.print("<br>??<br>"); out.printf(format, "??", item.getName()); } } out.println("</body>"); out.println("</html>"); } catch (FileUploadException e) { out.println(e + "<br>"); throw new ServletException(e); } catch (Exception e) { out.println(e + "<br>"); throw new ServletException(e); } finally { out.close(); } }