List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload getItemIterator
public FileItemIterator getItemIterator(HttpServletRequest request) throws FileUploadException, IOException
From source file:de.kp.ames.web.function.upload.UploadServiceImpl.java
public void doSetRequest(RequestContext ctx) { /*/* w w w . j a va2 s .co m*/ * The result of the upload request, returned * to the requestor; note, that the result must * be a text response */ boolean result = false; HttpServletRequest request = ctx.getRequest(); try { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { /* * Create new file upload handler */ ServletFileUpload upload = new ServletFileUpload(); /* * Parse the request */ FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream fileItem = iter.next(); if (fileItem.isFormField()) { // not supported } else { /* * Hook into the upload request to some virus scanning * using the scanner factory of this application */ byte[] bytes = FileUtil.getByteArrayFromInputStream(fileItem.openStream()); boolean checked = MalwareScanner.scanForViruses(bytes); if (checked) { String item = this.method.getAttribute(MethodConstants.ATTR_ITEM); String type = this.method.getAttribute(MethodConstants.ATTR_TYPE); if ((item == null) || (type == null)) { this.sendNotImplemented(ctx); } else { String fileName = FilenameUtils.getName(fileItem.getName()); String mimeType = fileItem.getContentType(); try { result = upload(item, type, fileName, mimeType, bytes); } catch (Exception e) { sendBadRequest(ctx, e); } } } } } } /* * Send html response */ if (result == true) { this.sendHTMLResponse(createHtmlSuccess(), ctx.getResponse()); } else { this.sendHTMLResponse(createHtmlFailure(), ctx.getResponse()); } } catch (Exception e) { this.sendBadRequest(ctx, e); } finally { } }
From source file:echopoint.tucana.JakartaCommonsFileUploadProvider.java
/** * @see UploadSPI#handleUpload(nextapp.echo.webcontainer.Connection , * FileUploadSelector, String, UploadProgress) *///ww w . ja v a2 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_2.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from www. j av a 2 s . 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 { 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:com.github.thorqin.toolkit.web.utility.UploadManager.java
/** * Save upload file to disk//from w w w. j av a 2 s . c o m * @param request HttpServletRequest * @param maxSize maximum size of the upload file, in bytes. * @return Saved file info list * @throws ServletException * @throws IOException * @throws FileUploadException */ public List<FileInfo> saveUploadFiles(HttpServletRequest request, int maxSize) throws ServletException, IOException, FileUploadException { List<FileInfo> uploadList = new LinkedList<>(); request.setCharacterEncoding("utf-8"); ServletFileUpload upload = new ServletFileUpload(); upload.setHeaderEncoding("UTF-8"); if (!ServletFileUpload.isMultipartContent(request)) { return uploadList; } upload.setSizeMax(maxSize); FileItemIterator iterator = upload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); try (InputStream stream = item.openStream()) { if (!item.isFormField()) { FileInfo info = new FileInfo(); info.setFileName(item.getName()); if (pattern != null && !pattern.matcher(info.fileName).matches()) { continue; } info = store(stream, info.fileName); uploadList.add(info); } } } return uploadList; }
From source file:com.artgameweekend.projects.art.web.TagUploadServlet.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try {// www . jav a 2 s. c o m // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); upload.setSizeMax(500000); res.setContentType(Constants.CONTENT_TYPE_TEXT); PrintWriter out = res.getWriter(); byte[] image = null; Tag tag = new Tag(); TagImage tagImage = new TagImage(); TagThumbnail tagThumbnail = new TagThumbnail(); String contentType = null; boolean bLandscape = false; try { FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream in = item.openStream(); if (item.isFormField()) { out.println("Got a form field: " + item.getFieldName()); if (Constants.PARAMATER_NAME.equals(item.getFieldName())) { tag.setName(IOUtils.toString(in)); } if (Constants.PARAMATER_LAT.equals(item.getFieldName())) { tag.setLat(Double.parseDouble(IOUtils.toString(in))); } if (Constants.PARAMATER_LON.equals(item.getFieldName())) { tag.setLon(Double.parseDouble(IOUtils.toString(in))); } if (Constants.PARAMATER_LANDSCAPE.equals(item.getFieldName())) { bLandscape = IOUtils.toString(in).equals("on"); } } else { String fieldName = item.getFieldName(); String fileName = item.getName(); contentType = item.getContentType(); out.println("--------------"); out.println("fileName = " + fileName); out.println("field name = " + fieldName); out.println("contentType = " + contentType); try { image = IOUtils.toByteArray(in); } finally { IOUtils.closeQuietly(in); } } } } catch (SizeLimitExceededException e) { out.println("You exceeded the maximum size (" + e.getPermittedSize() + ") of the file (" + e.getActualSize() + ")"); } contentType = (contentType != null) ? contentType : "image/jpeg"; if (bLandscape) { image = rotate(image); } tagImage.setImage(image); tagImage.setContentType(contentType); tagThumbnail.setImage(createThumbnail(image)); tagThumbnail.setContentType(contentType); TagImageDAO daoImage = new TagImageDAO(); daoImage.create(tagImage); TagThumbnailDAO daoThumbnail = new TagThumbnailDAO(); daoThumbnail.create(tagThumbnail); TagDAO dao = new TagDAO(); tag.setKeyImage(tagImage.getKey()); tag.setKeyThumbnail(tagThumbnail.getKey()); tag.setDate(new Date().getTime()); dao.create(tag); } catch (Exception ex) { throw new ServletException(ex); } }
From source file:com.fullmetalgalaxy.server.AccountServlet.java
@Override protected void doPost(HttpServletRequest p_request, HttpServletResponse p_response) throws ServletException, IOException { ServletFileUpload upload = new ServletFileUpload(); Map<String, String> params = new HashMap<String, String>(); boolean isConnexion = false; boolean isPassword = false; try {/* w w w . j a v a2 s.c om*/ // Parse the request FileItemIterator iter = upload.getItemIterator(p_request); while (iter.hasNext()) { FileItemStream item = iter.next(); if (item.isFormField()) { if (item.getFieldName().equalsIgnoreCase("connexion")) { isConnexion = true; } if (item.getFieldName().equalsIgnoreCase("password")) { isPassword = true; } params.put(item.getFieldName(), Streams.asString(item.openStream(), "UTF-8")); } } } catch (FileUploadException e) { log.error(e); } if (isConnexion) { // user try to connect with an FMG account boolean isConnected = true; isConnected = connectFmgUser(p_request, p_response, params); if (isConnected) { String continueUrl = params.get("continue"); if (continueUrl == null) { // by default, my games is the default url continueUrl = "/gamelist.jsp"; } p_response.sendRedirect(continueUrl); } return; } else if (isPassword) { // user ask for his password to be send on his email String msg = ""; FmgDataStore ds = new FmgDataStore(false); Query<EbAccount> query = ds.query(EbAccount.class).filter("m_email", params.get("email")); QueryResultIterator<EbAccount> it = query.iterator(); if (!it.hasNext()) { msg = "l'adresse mail " + params.get("email") + " n'a pas t trouv"; } else { EbAccount account = it.next(); if (account.getLastPasswordAsk() != null && account.getLastPasswordAsk() .getTime() > System.currentTimeMillis() - (1000 * 60 * 60 * 24)) { msg = "une seule demande par jour"; } else if (account.getAuthProvider() != AuthProvider.Fmg) { msg = "ce compte FMG est associ a un compte google"; } else { // all is ok, send a mail new FmgMessage("askPassword").sendEMail(account); msg = "un email a t envoy " + account.getEmail(); account.setLastPasswordAsk(new Date()); ds.put(account); } } ds.close(); p_response.sendRedirect("/password.jsp?msg=" + msg); return; } else { // update or create new account String msg = checkParams(params); if (msg != null) { p_response.sendRedirect("/account.jsp?msg=" + msg); return; } msg = saveAccount(p_request, p_response, params); if (msg != null) { p_response.sendRedirect("/account.jsp?msg=" + msg); return; } else { if (!Auth.isUserLogged(p_request, p_response)) { Auth.connectUser(p_request, params.get("login")); } if ("0".equalsIgnoreCase(params.get("accountid"))) { // return page new games p_response.sendRedirect("/gamelist.jsp?tab=0"); } else { // stay editing profile p_response.sendRedirect("/profile.jsp?id=" + params.get("accountid")); } return; } } }
From source file:edu.stanford.epad.epadws.handlers.dicom.DSOUtil.java
public static boolean handleCreateDSO(String projectID, String subjectID, String studyUID, String seriesUID, HttpServletRequest httpRequest, PrintWriter responseStream, String username) { // See http://www.tutorialspoint.com/servlets/servlets-file-uploading.htm boolean uploadError = false; log.info("Received DSO create request for series " + seriesUID); try {/* w w w . jav a 2 s . c o m*/ ServletFileUpload servletFileUpload = new ServletFileUpload(); FileItemIterator fileItemIterator = servletFileUpload.getItemIterator(httpRequest); DSOEditRequest dsoEditRequest = null; String editedFrameNumbers = httpRequest.getParameter("editedFrameNumbers"); if (editedFrameNumbers == null || editedFrameNumbers.length() == 0) { dsoEditRequest = extractDSOEditRequest(fileItemIterator); } else { log.info("Uploaded mask frame numbers:" + editedFrameNumbers); String[] frameNumbers = editedFrameNumbers.split(","); List<Integer> numbers = new ArrayList<Integer>(); for (String frameNumber : frameNumbers) { if (frameNumber.trim().length() == 0) continue; numbers.add(new Integer(frameNumber.trim())); } dsoEditRequest = new DSOEditRequest(projectID, subjectID, studyUID, seriesUID, "", "", numbers); } //need to pass this all the way to segmentation writer, put into edit request String property = httpRequest.getParameter("property"); String color = httpRequest.getParameter("color"); dsoEditRequest.property = property; dsoEditRequest.color = color; log.info("DSOCreateRequest, seriesUID:" + dsoEditRequest.seriesUID + " imageUID:" + dsoEditRequest.imageUID + " aimID:" + dsoEditRequest.aimID + " number Frames:" + dsoEditRequest.editedFrameNumbers.size()); if (dsoEditRequest != null) { List<File> framesPNGMaskFiles = HandlerUtil.extractFiles(fileItemIterator, "DSOFrame", ".PNG"); if (framesPNGMaskFiles.isEmpty()) { log.warning("No PNG masks supplied in DSO create request for series " + seriesUID); uploadError = true; } else { framesPNGMaskFiles = framesPNGMaskFiles.subList(0, dsoEditRequest.editedFrameNumbers.size()); log.info("Extracted " + framesPNGMaskFiles.size() + " file mask(s) for DSO create for series " + seriesUID); String name = httpRequest.getParameter("name"); DSOEditResult dsoEditResult = DSOUtil.createNewDSO(name, dsoEditRequest, framesPNGMaskFiles, projectID, username); if (dsoEditResult != null) { responseStream.append(dsoEditResult.toJSON()); } else { log.info("Null return from createNewDSO"); uploadError = true; } } } else { log.warning("Invalid JSON header in DSO edit request for series " + seriesUID); uploadError = true; } } catch (IOException e) { log.warning("IO exception handling DSO edits for series " + seriesUID, e); uploadError = true; } catch (FileUploadException e) { log.warning("File upload exception handling DSO edits for series " + seriesUID, e); uploadError = true; } if (!uploadError) log.info("DSO successfully created ..."); return uploadError; }
From source file:com.google.livingstories.servlet.DataImportServlet.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { startTime = System.currentTimeMillis(); message = ""; if (req.getContentType().contains("multipart/form-data")) { try {//from w w w . j a va 2 s . co m ServletFileUpload upload = new ServletFileUpload(); JSONObject data = null; boolean override = false; FileItemIterator iter = upload.getItemIterator(req); while (iter.hasNext()) { FileItemStream item = iter.next(); if (item.getFieldName().equals("override")) { override = true; } else if (item.getFieldName().equals("data")) { data = new JSONObject(Streams.asString(item.openStream())); } } checkRunState(override); inputData = data; setUp(); } catch (FileUploadException ex) { throw new RuntimeException(ex); } catch (JSONException ex) { throw new RuntimeException(ex); } } try { process(); } catch (Exception ex) { Writer result = new StringWriter(); PrintWriter printWriter = new PrintWriter(result); ex.printStackTrace(printWriter); message = result.toString(); runState = RunState.ERROR; } finally { if (runState != RunState.RUNNING) { tearDown(); } Caches.clearAll(); } resp.setContentType("text/html"); resp.getWriter().append(message + "<br>" + runState.name()); }
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 {//from ww w.ja v a 2 s. co 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:com.github.davidcarboni.encryptedfileupload.SizesTest.java
@Test public void testMaxSizeLimitUnknownContentLength() throws IOException, FileUploadException { final String request = "-----1234\r\n" + "Content-Disposition: form-data; name=\"file1\"; filename=\"foo1.tab\"\r\n" + "Content-Type: text/whatever\r\n" + "Content-Length: 10\r\n" + "\r\n" + "This is the content of the file\n" + "\r\n" + "-----1234\r\n" + "Content-Disposition: form-data; name=\"file2\"; filename=\"foo2.tab\"\r\n" + "Content-Type: text/whatever\r\n" + "\r\n" + "This is the content of the file\n" + "\r\n" + "-----1234--\r\n"; ServletFileUpload upload = new ServletFileUpload(new EncryptedFileItemFactory()); upload.setFileSizeMax(-1);//from w w w.ja v a2 s.c om upload.setSizeMax(300); // the first item should be within the max size limit // set the read limit to 10 to simulate a "real" stream // otherwise the buffer would be immediately filled MockHttpServletRequest req = new MockHttpServletRequest(request.getBytes("US-ASCII"), CONTENT_TYPE); req.setContentLength(-1); req.setReadLimit(10); FileItemIterator it = upload.getItemIterator(req); assertTrue(it.hasNext()); FileItemStream item = it.next(); assertFalse(item.isFormField()); assertEquals("file1", item.getFieldName()); assertEquals("foo1.tab", item.getName()); { @SuppressWarnings("resource") // Streams.copy closes the input file InputStream stream = item.openStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Streams.copy(stream, baos, true); } // the second item is over the size max, thus we expect an error try { // the header is still within size max -> this shall still succeed assertTrue(it.hasNext()); } catch (Exception e) { // FileUploadBase.SizeException has protected access: if (e.getClass().getSimpleName().equals("SizeException")) { fail(); } else { throw e; } } item = it.next(); try { @SuppressWarnings("resource") // Streams.copy closes the input file InputStream stream = item.openStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Streams.copy(stream, baos, true); fail(); } catch (FileUploadIOException e) { // expected } }