List of usage examples for org.apache.commons.fileupload FileItemStream isFormField
boolean isFormField();
FileItem
instance represents a simple form field. From source file:fedora.server.rest.RestUtil.java
/** * Retrieves the contents of the HTTP Request. * @return InputStream from the request/* w w w . j a va 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: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 {//w w w . jav 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:echopoint.tucana.JakartaCommonsFileUploadProvider.java
/** * @see UploadSPI#handleUpload(nextapp.echo.webcontainer.Connection , * FileUploadSelector, String, UploadProgress) */// w w w. j a v a 2 s.c om @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:market.servlet.Upload.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from ww w . jav a 2s . 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 { ServletFileUpload upload = new ServletFileUpload(); upload.setSizeMax(50000); response.setContentType("xml"); PrintWriter out = response.getWriter(); String user = request.getParameter("user"); String fileContents = ""; try { /*capture submitted data*/ FileItemIterator iterator = upload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream in = item.openStream(); if (item.isFormField()) { /*do nothing*/ } else { try { fileContents = IOUtils.toString(in); // MarketParser parser = new MarketParser(fileContents); new MarketHandler(fileContents, user); response.sendRedirect("./home"); } finally { IOUtils.closeQuietly(in); } } } } catch (SizeLimitExceededException e) { out.println("You exceeded the maximu size (" + e.getPermittedSize() + ") of the file (" + e.getActualSize() + ")"); } catch (FileUploadException ex) { Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:edu.caltech.ipac.firefly.server.servlets.AnyFileUpload.java
protected void processRequest(HttpServletRequest req, HttpServletResponse res) throws Exception { String dest = req.getParameter(DEST_PARAM); String preload = req.getParameter(PRELOAD_PARAM); String overrideCacheKey = req.getParameter(CACHE_KEY); String fileType = req.getParameter(FILE_TYPE); if (!ServletFileUpload.isMultipartContent(req)) { sendReturnMsg(res, 400, "Is not a Multipart request. Request rejected.", ""); }/*www .j a va 2 s . c o m*/ StopWatch.getInstance().start("Upload File"); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(req); while (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { String fileName = item.getName(); InputStream inStream = new BufferedInputStream(item.openStream(), IpacTableUtil.FILE_IO_BUFFER_SIZE); String ext = resolveExt(fileName); FileType fType = resolveType(fileType, ext, item.getContentType()); File destDir = resolveDestDir(dest, fType); boolean doPreload = resolvePreload(preload, fType); File uf = File.createTempFile("upload_", ext, destDir); String rPathInfo = ServerContext.replaceWithPrefix(uf); UploadFileInfo fi = new UploadFileInfo(rPathInfo, uf, fileName, item.getContentType()); String fileCacheKey = overrideCacheKey != null ? overrideCacheKey : rPathInfo; UserCache.getInstance().put(new StringKey(fileCacheKey), fi); if (doPreload && fType == FileType.FITS) { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(uf), IpacTableUtil.FILE_IO_BUFFER_SIZE); TeeInputStream tee = new TeeInputStream(inStream, bos); try { final Fits fits = new Fits(tee); FitsRead[] frAry = FitsRead.createFitsReadArray(fits); FitsCacher.addFitsReadToCache(uf, frAry); } finally { FileUtil.silentClose(bos); FileUtil.silentClose(tee); } } else { FileUtil.writeToFile(inStream, uf); } sendReturnMsg(res, 200, null, fileCacheKey); Counters.getInstance().increment(Counters.Category.Upload, fi.getContentType()); return; } } StopWatch.getInstance().printLog("Upload File"); }
From source file:fi.helsinki.lib.simplerest.CollectionLogoResource.java
@Put public Representation put(Representation logoRepresentation) { Context c = null;// ww w.jav a 2 s . c o m 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;/*from w w w . j a v a 2 s.com*/ 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 {/*w w w .j a va 2 s . com*/ // 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:foo.domaintest.http.HttpApiModuleTest.java
FileItemStream createItem(String name, String value, boolean isFormField) throws Exception { FileItemStream item = mock(FileItemStream.class); when(item.isFormField()).thenReturn(isFormField); when(isFormField ? item.getFieldName() : item.getName()).thenReturn(name); // Use UTF_16 and specify it to provideParameterMap to make sure we honor the request encoding. when(item.openStream()).thenReturn(new ByteArrayInputStream(value.getBytes(UTF_16))); return item;//from w ww. j a va 2s .com }
From source file:kg12.Ex12_1.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from ww w . j a va 2s. 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 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(); } }