List of usage examples for org.apache.commons.fileupload FileItemStream isFormField
boolean isFormField();
FileItem
instance represents a simple form field. From source file:com.github.terma.gigaspacewebconsole.server.ImportServlet.java
private void safeDoPost(final HttpServletRequest request) throws Exception { final ServletFileUpload upload = new ServletFileUpload(); final FileItemIterator iterator = upload.getItemIterator(request); ImportRequest importRequest = null;//from ww w. jav a2s. co m String inputFile = null; InputStream inputStream = null; while (iterator.hasNext()) { final FileItemStream item = iterator.next(); final String name = item.getFieldName(); final InputStream stream = item.openStream(); if (item.isFormField()) { if ("json".equals(name)) { importRequest = gson.fromJson(Streams.asString(stream), ImportRequest.class); } } else { inputFile = item.getName(); inputStream = stream; break; } } if (importRequest == null) throw new IOException("Expect 'json' parameter!"); if (inputStream == null) throw new IOException("Expect file to import!"); importRequest.file = inputFile; ProviderResolver.getProvider(importRequest.driver).import1(importRequest, inputStream); }
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(); }/* w w w . j av a 2s.co 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.threewks.thundr.bind.http.MultipartHttpBinder.java
void extractParameters(HttpServletRequest req, Map<String, List<String>> formFields, Map<String, MultipartFile> fileFields) { try {//from ww w.j a v a2 s .c om FileItemIterator itemIterator = upload.getItemIterator(req); while (itemIterator.hasNext()) { FileItemStream item = itemIterator.next(); InputStream stream = item.openStream(); String fieldName = item.getFieldName(); if (item.isFormField()) { List<String> existing = formFields.get(fieldName); if (existing == null) { existing = new LinkedList<String>(); formFields.put(fieldName, existing); } existing.add(Streams.readString(stream)); } else { MultipartFile file = new MultipartFile(item.getName(), Streams.readBytes(stream), item.getContentType()); fileFields.put(fieldName, file); } stream.close(); } } catch (Exception e) { throw new BindException(e, "Failed to bind multipart form data: %s", e.getMessage()); } }
From source file:hudson.gwtmarketplace.server.ImageUploadServlet.java
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); ServletFileUpload upload = new ServletFileUpload(); Map<String, String> parameters = new HashMap<String, String>(); Image resizedImage = null;/* w ww . j a v a2 s.c o m*/ try { // 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()) { parameters.put(name, toString(stream)); } else { resizedImage = resize(stream); } } } catch (Exception e) { response.sendError(500); } String productId = parameters.get("key"); if (null != productId && null != resizedImage) { try { String iconKey = productMgr.setImageData(Long.parseLong(productId), resizedImage.getImageData()); if (null != iconKey) { response.getOutputStream().write(iconKey.getBytes()); } } catch (InvalidAccessException e) { e.printStackTrace(); } } }
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 v a2s . 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()); } }
From source file:de.mpg.imeji.presentation.upload.UploadServlet.java
/** * Download the file on the disk in a tmp file * * @param req//from ww w. j av a 2s .c om * @return * @throws FileUploadException * @throws IOException */ private UploadItem doUpload(HttpServletRequest req) { try { final ServletFileUpload upload = new ServletFileUpload(); final FileItemIterator iter = upload.getItemIterator(req); UploadItem uploadItem = new UploadItem(); while (iter.hasNext()) { final FileItemStream fis = iter.next(); if (!fis.isFormField()) { uploadItem.setFilename(fis.getName()); final File tmp = TempFileUtil.createTempFile("upload", null); StorageUtils.writeInOut(fis.openStream(), new FileOutputStream(tmp), true); uploadItem.setFile(tmp); } else { ByteArrayOutputStream out = new ByteArrayOutputStream(); StorageUtils.writeInOut(fis.openStream(), out, true); uploadItem.getParams().put(fis.getFieldName(), out.toString("UTF-8")); } } return uploadItem; } catch (final Exception e) { LOGGER.error("Error file upload", e); } return new UploadItem(); }
From source file:fi.jyu.student.jatahama.onlineinquirytool.server.LoadSaveServlet.java
@Override public final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { try {// w ww .java 2 s . c o m // 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:kg12.Ex12_2.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* ww w. ja va 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 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_2</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()); InputStream is = item.openStream(); String fileName = item.getName(); int len = 0; byte[] buffer = new byte[fileSizeMax]; FileOutputStream fos = new FileOutputStream( "D:\\NetBeansProjects\\ap2_www\\web\\kg12\\" + fileName); try { while ((len = is.read(buffer)) > 0) { fos.write(buffer, 0, len); } } finally { fos.close(); } } } 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(); } }
From source file:jetbrick.web.mvc.multipart.CommonsFileUpload.java
@Override public MultipartRequest transform(HttpServletRequest request) throws IOException { String contextType = request.getHeader("Content-Type"); if (contextType == null || !contextType.startsWith("multipart/form-data")) { return null; }// w w w . j av a2s.c om String encoding = request.getCharacterEncoding(); MultipartRequest req = new MultipartRequest(request); ServletFileUpload upload = new ServletFileUpload(); upload.setHeaderEncoding(encoding); try { FileItemIterator it = upload.getItemIterator(request); while (it.hasNext()) { FileItemStream item = it.next(); String fieldName = item.getFieldName(); InputStream stream = item.openStream(); try { if (item.isFormField()) { req.setParameter(fieldName, Streams.asString(stream, encoding)); } else { String originalFilename = item.getName(); if (originalFilename == null || originalFilename.length() == 0) { continue; } File diskFile = UploadUtils.getUniqueTemporaryFile(originalFilename); OutputStream fos = new FileOutputStream(diskFile); try { IoUtils.copy(stream, fos); } finally { IoUtils.closeQuietly(fos); } FilePart filePart = new FilePart(fieldName, originalFilename, diskFile); req.addFile(filePart); } } finally { IoUtils.closeQuietly(stream); } } } catch (FileUploadException e) { throw new IllegalStateException(e); } return req; }
From source file:com.woonoz.proxy.servlet.HttpEntityEnclosingRequestHandler.java
private String getContentTypeForFileItem(FileItemStream fileItem) { final String contentType = fileItem.getContentType(); if (contentType != null) { return contentType; } else {//from ww w . jav a2s. c o m if (fileItem.isFormField()) { return "text/plain"; } else { return "application/octet-stream"; } } }