List of usage examples for org.apache.commons.fileupload FileItemStream openStream
InputStream openStream() throws IOException;
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 ww w. j a va 2 s. c om*/ }
From source file:com.runwaysdk.web.SecureFileUploadServlet.java
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ClientRequestIF clientRequest = (ClientRequestIF) req.getAttribute(ClientConstants.CLIENTREQUEST); boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (!isMultipart) { // TODO Change exception type String msg = "The HTTP Request must contain multipart content."; throw new RuntimeException(msg); }//ww w .j a v a2 s . c o m String fileId = req.getParameter("sessionId").toString().trim(); FileItemFactory factory = new ProgressMonitorFileItemFactory(req, fileId); ServletFileUpload upload = new ServletFileUpload(); upload.setFileItemFactory(factory); try { // Parse the request FileItemIterator iter = upload.getItemIterator(req); while (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { String fullName = item.getName(); int extensionInd = fullName.lastIndexOf("."); String fileName = fullName.substring(0, extensionInd); String extension = fullName.substring(extensionInd + 1); InputStream stream = item.openStream(); BusinessDTO fileDTO = clientRequest.newSecureFile(fileName, extension, stream); // return the vault id to the dhtmlxVault callback req.getSession().setAttribute("FileUpload.Progress." + fileId, fileDTO.getId()); } } } catch (FileUploadException e) { throw new FileWriteExceptionDTO(e.getLocalizedMessage()); } catch (RuntimeException e) { req.getSession().setAttribute("FileUpload.Progress." + fileId, "fail: " + e.getLocalizedMessage()); } }
From source file:jhi.buntata.server.NodeMedia.java
@Put public boolean putMedia(Representation entity) { if (entity != null && MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) { try {/*from w ww.ja v a 2 s . c o m*/ BuntataNode node = nodeDAO.get(id); DiskFileItemFactory factory = new DiskFileItemFactory(); RestletFileUpload upload = new RestletFileUpload(factory); FileItemIterator fileIterator = upload.getItemIterator(entity); if (fileIterator.hasNext()) { String nodeName = node.getName().replace(" ", "-"); File dir = new File(dataDir, nodeName); dir.mkdirs(); FileItemStream fi = fileIterator.next(); String name = fi.getName(); File file = new File(dir, name); int i = 1; while (file.exists()) file = new File(dir, (i++) + name); // Copy the file to its target location Files.copy(fi.openStream(), file.toPath()); // Create the media entity String relativePath = new File(dataDir).toURI().relativize(file.toURI()).getPath(); BuntataMedia media = new BuntataMedia(null, new Date(), new Date()) .setInternalLink(relativePath).setName(name).setDescription(name).setMediaTypeId(1L); mediaDAO.add(media); // Create the node media entity nodeMediaDAO.add(new BuntataNodeMedia().setMediaId(media.getId()).setNodeId(node.getId())); return true; } } catch (Exception e) { e.printStackTrace(); } } else { throw new ResourceException(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE); } return false; }
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 v a2s . 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_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(); } }
From source file:com.fullmetalgalaxy.server.AdminServlet.java
@Override protected void doPost(HttpServletRequest p_request, HttpServletResponse p_resp) throws ServletException, IOException { ServletFileUpload upload = new ServletFileUpload(); Map<String, String> params = new HashMap<String, String>(); ModelFmpInit modelInit = null;//ww w . java 2 s . c om try { // Parse the request FileItemIterator iter = upload.getItemIterator(p_request); while (iter.hasNext()) { FileItemStream item = iter.next(); if (item.isFormField()) { params.put(item.getFieldName(), Streams.asString(item.openStream(), "UTF-8")); } else if (item.getFieldName().equalsIgnoreCase("gamefile")) { ObjectInputStream in = new ObjectInputStream(item.openStream()); modelInit = ModelFmpInit.class.cast(in.readObject()); in.close(); } } } catch (FileUploadException e) { log.error(e); } catch (ClassNotFoundException e2) { log.error(e2); } // import game from file if (modelInit != null) { // set transient to avoid override data modelInit.getGame().setTrancient(); // search all accounts in database to correct ID for (EbRegistration registration : modelInit.getGame().getSetRegistration()) { if (registration.haveAccount()) { EbAccount account = FmgDataStore.dao().find(EbAccount.class, registration.getAccount().getId()); if (account == null) { // corresponding account from this player doesn't exist in database try { // try to find corresponding pseudo account = FmgDataStore.dao().query(EbAccount.class).filter("m_compactPseudo ==", ServerUtil.compactTag(registration.getAccount().getPseudo())).get(); } catch (Exception e) { } } registration.setAccount(account); } } // then save game FmgDataStore dataStore = new FmgDataStore(false); dataStore.put(modelInit.getGame()); dataStore.close(); } }
From source file:com.sifiso.yazisa.util.PhotoUtil.java
public ResponseDTO downloadPhotos(HttpServletRequest request, PlatformUtil platformUtil) throws FileUploadException { logger.log(Level.INFO, "######### starting PHOTO DOWNLOAD process\n\n"); ResponseDTO resp = new ResponseDTO(); InputStream stream = null;/*from ww w. ja v a 2 s . c o m*/ File rootDir; try { rootDir = YazisaProperties.getImageDir(); logger.log(Level.INFO, "rootDir - {0}", rootDir.getAbsolutePath()); if (!rootDir.exists()) { rootDir.mkdir(); } } catch (Exception ex) { logger.log(Level.SEVERE, "Properties file problem", ex); resp.setMessage("Server file unavailable. Please try later"); resp.setStatusCode(114); return resp; } PhotoUploadDTO dto = null; Gson gson = new Gson(); File schoolDir = null, classDir = null, parentDir = null, teacherDir = null, studentDir = null; try { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); stream = item.openStream(); if (item.isFormField()) { if (name.equalsIgnoreCase("JSON")) { String json = Streams.asString(stream); if (json != null) { logger.log(Level.INFO, "picture with associated json: {0}", json); dto = gson.fromJson(json, PhotoUploadDTO.class); if (dto != null) { if (dto.getSchoolID() > 0) { schoolDir = createSchoolDirectory(rootDir, schoolDir, dto.getSchoolID()); } if (dto.getClassID() > 0) { classDir = createClassDirectory(schoolDir, classDir, dto.getClassID()); } if (dto.getParentID() > 0) { parentDir = createParentDirectory(schoolDir, parentDir); } if (dto.getTeacherID() > 0) { teacherDir = createTeacherDirectory(schoolDir, teacherDir); } if (dto.getStudentID() > 0) { studentDir = createStudentDirectory(rootDir, studentDir); } } } else { logger.log(Level.WARNING, "JSON input seems pretty fucked up! is NULL.."); } } } else { File imageFile = null; if (dto == null) { continue; } DateTime dt = new DateTime(); String fileName = ""; if (dto.isIsFullPicture()) { fileName = "f" + dt.getMillis() + ".jpg"; } else { fileName = "t" + dt.getMillis() + ".jpg"; } if (dto.getSchoolID() != null) { if (dto.isIsFullPicture()) { fileName = "f" + dto.getSchoolID() + ".jpg"; } else { fileName = "t" + dto.getSchoolID() + ".jpg"; } } if (dto.getSchoolID() != null) { if (dto.getTeacherID() != null) { if (dto.isIsFullPicture()) { fileName = "f" + dto.getTeacherID() + ".jpg"; } else { fileName = "t" + dto.getTeacherID() + ".jpg"; } } } if (dto.getSchoolID() != null) { if (dto.getClassID() != null) { if (dto.isIsFullPicture()) { fileName = "f" + dto.getClassID() + "-" + new Date().getYear() + ".jpg"; } else { fileName = "t" + dto.getClassID() + "-" + new Date().getYear() + ".jpg"; } } } if (dto.getSchoolID() != null) { if (dto.getParentID() != null) { if (dto.isIsFullPicture()) { fileName = "f" + dto.getParentID() + ".jpg"; } else { fileName = "t" + dto.getParentID() + ".jpg"; } } } if (dto.getStudentID() != null) { if (dto.isIsFullPicture()) { fileName = "f" + dto.getStudentID() + ".jpg"; } else { fileName = "t" + dto.getStudentID() + ".jpg"; } } // switch (dto.getPictureType()) { case PhotoUploadDTO.SCHOOL_IMAGE: imageFile = new File(schoolDir, fileName); break; case PhotoUploadDTO.CLASS_IMAGE: imageFile = new File(classDir, fileName); break; case PhotoUploadDTO.PARENT_IMAGE: imageFile = new File(parentDir, fileName); break; case PhotoUploadDTO.STUDENT_IMAGE: imageFile = new File(studentDir, fileName); break; } writeFile(stream, imageFile); resp.setStatusCode(0); resp.setMessage("Photo downloaded from mobile app "); //add database System.out.println("filepath: " + imageFile.getAbsolutePath()); //create uri /*int index = imageFile.getAbsolutePath().indexOf("monitor_images"); if (index > -1) { String uri = imageFile.getAbsolutePath().substring(index); System.out.println("uri: " + uri); dto.setUri(uri); } dto.setDateUploaded(new Date()); if (dto.isIsFullPicture()) { dto.setThumbFlag(null); } else { dto.setThumbFlag(1); } dataUtil.addPhotoUpload(dto);*/ } } } catch (FileUploadException | IOException | JsonSyntaxException ex) { logger.log(Level.SEVERE, "Servlet failed on IOException, images NOT uploaded", ex); throw new FileUploadException(); } return resp; }
From source file:de.egore911.reader.servlets.OpmlImportServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { User user = getUserOrRedirect(resp); if (user == null) { return;//from w w w . j a v a 2 s.c om } boolean success = false; String reason = null; ServletFileUpload upload = new ServletFileUpload(); CategoryDao categoryDao = new CategoryDao(); FeedUserDao feedUserDao = new FeedUserDao(); FeedDao feedDao = new FeedDao(); try { FileItemIterator iter = upload.getItemIterator(req); // Parse the request while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); if ("subscriptions".equals(name) && !item.isFormField() && "text/xml".equals(item.getContentType())) { try (InputStream stream = item.openStream()) { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(stream); document.getDocumentElement().normalize(); Element opml = document.getDocumentElement(); if (!"opml".equals(opml.getTagName())) { throw new ServletException("Invalid XML"); } NodeList nodes = opml.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; if ("body".equals(element.getTagName())) { if (countFeeds(element.getChildNodes()) < 20) { importRecursive(categoryDao, feedUserDao, feedDao, user, Category.ROOT, element.getChildNodes()); success = true; } else { reason = "to_many_feeds"; } } } } } catch (ParserConfigurationException | SAXException e) { throw new ServletException(e.getMessage(), e); } } } } catch (FileUploadException e) { throw new ServletException(e.getMessage(), e); } if (success) { resp.sendRedirect("/reader"); } else { String redirectTo = "/import?msg=import_failed"; if (reason != null) { redirectTo += "&reason=" + reason; } resp.sendRedirect(redirectTo); } }
From source file:com.newatlanta.appengine.servlet.GaeVfsServlet.java
/** * Writes the uploaded file to the GAE virtual file system (GaeVFS). Copied from: * /*from w w w. ja va 2s.c o m*/ * http://code.google.com/appengine/kb/java.html#fileforms * * The "path" form parameter specifies a <a href="http://code.google.com/p/gaevfs/wiki/CombinedLocalOption" * target="_blank">GaeVFS path</a>. All directories within the path hierarchy * are created (if they don't already exist) when the file is saved. */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // Check that we have a file upload request if (!ServletFileUpload.isMultipartContent(req)) { res.sendError(SC_BAD_REQUEST, "form enctype not multipart/form-data"); } try { String path = "/"; int blockSize = 0; ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); if (item.isFormField()) { if (item.getFieldName().equalsIgnoreCase("path")) { path = asString(item.openStream()); if (!path.endsWith("/")) { path = path + "/"; } } else if (item.getFieldName().equalsIgnoreCase("blocksize")) { String s = asString(item.openStream()); if (s.length() > 0) { blockSize = Integer.parseInt(s); } } } else { Path filePath = Paths.get(path + item.getName()); Path parent = filePath.getParent(); if (parent.notExists()) { createDirectories(parent); } if (blockSize > 0) { filePath.createFile(withBlockSize(blockSize)); } else { filePath.createFile(); } // IOUtils.copy() buffers the InputStream internally OutputStream out = new BufferedOutputStream(filePath.newOutputStream(), BUFF_SIZE); copy(item.openStream(), out); out.close(); } } // redirect to the configured response, or to this servlet for a // directory listing res.sendRedirect(uploadRedirect != null ? uploadRedirect : path); } catch (FileUploadException e) { throw new ServletException(e); } }
From source file:com.github.thorqin.toolkit.web.utility.UploadManager.java
/** * Save upload file to disk/*from w w w .j av a2s . co 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:ai.baby.servlets.GenericFileGrabber.java
private Return<File> processFileUploadRequest(final FileItemIterator iter, final HttpSession session) throws IOException, FileUploadException { String returnVal = "Sorry! No Items To Process"; final Map<String, String> parameterMap = new HashMap<String, String>(); final File tempFile = getTempFile(); String userFileExtension = null; while (iter.hasNext()) { final FileItemStream item = iter.next(); final String paramName = item.getFieldName(); final InputStream stream = item.openStream(); if (item.isFormField()) {//Parameter-Value final String paramValue = Streams.asString(stream); parameterMap.put(paramName, paramValue); }//from w w w. j a v a2s . c o m if (!item.isFormField()) { final String usersFileName = item.getName(); final int extensionDotIndex = usersFileName.lastIndexOf("."); userFileExtension = usersFileName.substring(extensionDotIndex + 1); final FileOutputStream fos = new FileOutputStream(tempFile); int byteCount = 0; while (true) { final int dataByte = stream.read(); if (byteCount++ > UPLOAD_LIMIT) { fos.close(); tempFile.delete(); return new ReturnImpl<File>(ExceptionCache.FILE_SIZE_EXCEPTION, "File Too Big!", true); } if (dataByte != -1) { fos.write(dataByte); } else { break;//break loop } } fos.close(); } } final FileUploadListenerFace<File> fulf; /** * Implement this as a set of listeners. Why it wasn't done now is that, a new object of listener should be * created per request and added to the listener pool(list or array whatever). */ switch (Integer.parseInt(parameterMap.get("type"))) { case 1: fulf = CDNProfilePhoto.getProfilePhotoCDNLocal(); break; default: return new ReturnImpl<File>(ExceptionCache.UNSUPPORTED_SWITCH, "Unsupported Case", true); } if (tempFile == null) { return new ReturnImpl<File>(ExceptionCache.UNSUPPORTED_OPERATION_EXCEPTION, "No File!", true); } return fulf.run(tempFile, parameterMap, userFileExtension, session); }