List of usage examples for org.apache.commons.fileupload FileItem write
void write(File file) throws Exception;
From source file:com.krawler.esp.handlers.FileUploadHandler.java
public void uploadImage(FileItem fileItem, String fileName, String destinationDirectory, int width, int height, boolean company, boolean original) throws ServiceException { try {/*from w ww . j a v a2 s.c o m*/ File destDir = new File(destinationDirectory); if (!destDir.exists()) { destDir.mkdirs(); } File temp = new File(destinationDirectory, "temp_" + fileItem.getName()); fileItem.write(temp); String fName = (fileName.contains(".") ? fileName.substring(0, fileName.lastIndexOf(".")) : fileName); imgResize(temp.getAbsolutePath(), width, height, destinationDirectory + "/" + fName, company, original); temp.delete(); } catch (Exception e) { throw ServiceException.FAILURE("FileUploadHandler.uploadImage", e); } }
From source file:Controllers.AddItem.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from w w w . ja v a2s. c o m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = null; String itemCode = null; String price = null; String quantity = null; String category = null; String image = null; HttpSession session = request.getSession(true); User user = (User) session.getAttribute("user"); if (user == null) { response.sendRedirect("login"); return; } // request.getServletContext().getRealPath("/uploads"); String path = request.getServletContext().getRealPath("/uploads"); System.out.println(path); if (ServletFileUpload.isMultipartContent(request)) { try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); // new File(path).mkdirs(); File directory = new File(path + File.separator + fileName); image = fileName; item.write(directory); } else { if ("name".equals(item.getFieldName())) { name = item.getString(); } else if ("itemCode".equals(item.getFieldName())) { itemCode = item.getString(); } else if ("price".equals(item.getFieldName())) { price = item.getString(); } else if ("quantity".equals(item.getFieldName())) { quantity = item.getString(); } else if ("category".equals(item.getFieldName())) { category = item.getString(); } } } //File uploaded successfully System.out.println("done"); } catch (Exception ex) { ex.printStackTrace(); } } boolean status = ItemRepository.saveItem(name, itemCode, price, quantity, category, image, user); String message; if (status) { message = "Item saved successfully"; response.sendRedirect("dashboard"); } else { message = "Item not saved !!"; request.setAttribute("message", message); request.getRequestDispatcher("dashboard/addItem.jsp").forward(request, response); } }
From source file:hoot.services.ingest.MultipartSerializer.java
protected void _serializeUploadedFiles(List<FileItem> fileItemsList, String jobId, Map<String, String> uploadedFiles, Map<String, String> uploadedFilesPaths, String repFolderPath) throws Exception { Iterator<FileItem> fileItemsIterator = fileItemsList.iterator(); while (fileItemsIterator.hasNext()) { FileItem fileItem = fileItemsIterator.next(); String fileName = fileItem.getName(); if (fileName == null) { ResourceErrorHandler.handleError("A valid file name was not specified.", Status.BAD_REQUEST, log); }//from w w w . ja v a2 s . c om String uploadedPath = repFolderPath + "/" + fileName; File file = new File(uploadedPath); fileItem.write(file); String[] nameParts = fileName.split("\\."); if (nameParts.length > 1) { String extension = nameParts[nameParts.length - 1].toUpperCase(); String[] subArr = ArrayUtils.removeElement(nameParts, nameParts[nameParts.length - 1]); String filename = StringUtils.join(subArr, '.'); if (extension.equalsIgnoreCase("OSM") || extension.equalsIgnoreCase("SHP") || extension.equalsIgnoreCase("ZIP")) { uploadedFiles.put(filename, extension); uploadedFilesPaths.put(filename, fileName); log.debug("Saving uploaded:" + filename); } } } }
From source file:gov.nist.appvet.tool.SynchronousService.java
public boolean saveFileUpload(FileItem fileItem, String outputFilePath) { try {// w w w . jav a2 s . c o m if (fileItem == null) { log.error("File item is NULL"); return false; } File file = new File(outputFilePath); fileItem.write(file); log.debug("Saved file " + outputFilePath); return true; } catch (IOException e) { log.error(e.getMessage()); return false; } catch (Exception e) { log.error(e.getMessage()); return false; } }
From source file:hoot.services.utils.MultipartSerializerTest.java
@Ignore @Test//from ww w.j a v a 2 s . c om @Category(UnitTest.class) public void TestserializeUploadedFiles() throws Exception { // homeFolder + "/upload/" + jobId + "/" + relPath; // Create dummy FGDB String jobId = "123-456-789-testosm"; String wkdirpath = HOME_FOLDER + "/upload/" + jobId; File workingDir = new File(wkdirpath); FileUtils.forceMkdir(workingDir); Assert.assertTrue(workingDir.exists()); FileItemFactory factory = new DiskFileItemFactory(16, null); String textFieldName = "textField"; FileItem item = factory.createItem(textFieldName, "application/octet-stream", true, "dummy1.osm"); String textFieldValue = "0123456789"; byte[] testFieldValueBytes = textFieldValue.getBytes(); try (OutputStream os = item.getOutputStream()) { os.write(testFieldValueBytes); } File out = new File(wkdirpath + "/buffer.tmp"); item.write(out); List<FileItem> fileItemsList = new ArrayList<>(); fileItemsList.add(item); Assert.assertTrue(out.exists()); Map<String, String> uploadedFiles = new HashMap<>(); Map<String, String> uploadedFilesPaths = new HashMap<>(); // MultipartSerializer.serializeUploadedFiles(fileItemsList, uploadedFiles, uploadedFilesPaths, wkdirpath); Assert.assertEquals("OSM", uploadedFiles.get("dummy1")); Assert.assertEquals("dummy1.osm", uploadedFilesPaths.get("dummy1")); File content = new File(wkdirpath + "/dummy1.osm"); Assert.assertTrue(content.exists()); FileUtils.forceDelete(workingDir); }
From source file:com.yanzhenjie.andserver.sample.response.RequestUploadHandler.java
/** * Parse file and save.//from w w w .j ava 2 s . co m * * @param request request. * @param saveDirectory save directory. * @throws Exception may be. */ private void processFileUpload(HttpRequest request, File saveDirectory) throws Exception { FileItemFactory factory = new DiskFileItemFactory(1024 * 1024, saveDirectory); HttpFileUpload fileUpload = new HttpFileUpload(factory); // Set upload process listener. // fileUpload.setProgressListener(new ProgressListener(){...}); List<FileItem> fileItems = fileUpload .parseRequest(new HttpUploadContext((HttpEntityEnclosingRequest) request)); for (FileItem fileItem : fileItems) { if (!fileItem.isFormField()) { // File param. // Attribute. // fileItem.getContentType(); // fileItem.getFieldName(); // fileItem.getName(); // fileItem.getSize(); // fileItem.getString(); File uploadedFile = new File(saveDirectory, fileItem.getName()); // ? fileItem.write(uploadedFile); } else { // General param. String key = fileItem.getName(); String value = fileItem.getString(); } } }
From source file:com.globalsight.everest.webapp.pagehandler.tm.management.RemoveTmHandler.java
/** * Invoke this PageHandler./*from w w w. j a v a 2s . c om*/ * * @param p_pageDescriptor * the page desciptor * @param p_request * the original request sent from the browser * @param p_response * the original response object * @param p_context * context the Servlet context */ public void invokePageHandler(WebPageDescriptor p_pageDescriptor, HttpServletRequest p_request, HttpServletResponse p_response, ServletContext p_context) throws ServletException, IOException, EnvoyServletException { HttpSession session = p_request.getSession(); SessionManager sessionMgr = (SessionManager) session.getAttribute(SESSION_MANAGER); m_userId = (String) session.getAttribute(WebAppConstants.USER_NAME); String action = (String) p_request.getParameter(TM_ACTION); ResourceBundle bundle = PageHandler.getBundle(session); String errorMsg = null; StringBuilder errors = new StringBuilder(); try { if (TM_ACTION_DELETE.equals(action) || TM_ACTION_DELETE_LANGUAGE.equals(action) || TM_ACTION_DELETE_TULISTING.equals(action)) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024000); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> fileItems = upload.parseRequest(p_request); String tmIdArray = (String) p_request.getParameter(TM_TM_ID); String language = null; File tmxFile = null; for (FileItem item : fileItems) { if (TM_TM_ID.equals(item.getFieldName())) { tmIdArray = item.getString(); } else if ("tmxFile".equals(item.getFieldName())) { tmxFile = File.createTempFile("GSTUListing", null); String fileName = item.getName(); item.write(tmxFile); } else if ("LanguageList".equals(item.getFieldName())) { language = item.getString(); } } String[] tmIds = tmIdArray.split(","); if (!TM_ACTION_DELETE_LANGUAGE.equals(action)) { language = null; } long tmId = -1l; errorMsg = removeTM(sessionMgr, tmIds, bundle, language, tmxFile); } else if (TM_ACTION_CANCEL.equals(action)) { TmRemover tmRemover = (TmRemover) sessionMgr.getAttribute(TM_REMOVER); tmRemover.cancelProcess(); } } catch (Throwable ex) { logger.error("Tm removal error", ex); sessionMgr.setAttribute(TM_ERROR, ex.getMessage()); } sessionMgr.setAttribute(TM_ERROR, errorMsg); super.invokePageHandler(p_pageDescriptor, p_request, p_response, p_context); }
From source file:hoot.services.ingest.MultipartSerializerTest.java
@Test @Category(UnitTest.class) public void TestserializeFGDB() throws Exception { String jobId = "123-456-789"; String wkdirpath = homeFolder + "/upload/" + jobId; File workingDir = new File(wkdirpath); FileUtils.forceMkdir(workingDir);//ww w.j ava 2 s. c o m org.junit.Assert.assertTrue(workingDir.exists()); List<FileItem> fileItemsList = new ArrayList<FileItem>(); FileItemFactory factory = new DiskFileItemFactory(16, null); String textFieldName = "textField"; FileItem item = factory.createItem(textFieldName, "application/octet-stream", true, "fgdbTest.gdb/dummy1.gdbtable"); String textFieldValue = "0123456789"; byte[] testFieldValueBytes = textFieldValue.getBytes(); OutputStream os = item.getOutputStream(); os.write(testFieldValueBytes); os.close(); File out = new File(wkdirpath + "/buffer.tmp"); item.write(out); fileItemsList.add(item); org.junit.Assert.assertTrue(out.exists()); Map<String, String> uploadedFiles = new HashMap<String, String>(); Map<String, String> uploadedFilesPaths = new HashMap<String, String>(); _ms._serializeFGDB(fileItemsList, jobId, uploadedFiles, uploadedFilesPaths); org.junit.Assert.assertEquals("GDB", uploadedFiles.get("fgdbTest")); org.junit.Assert.assertEquals("fgdbTest.gdb", uploadedFilesPaths.get("fgdbTest")); File fgdbpath = new File(wkdirpath + "/fgdbTest.gdb"); org.junit.Assert.assertTrue(fgdbpath.exists()); File content = new File(wkdirpath + "/fgdbTest.gdb/dummy1.gdbtable"); org.junit.Assert.assertTrue(content.exists()); FileUtils.forceDelete(workingDir); }
From source file:Controllers.EditItem.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from w w w . jav a2 s. c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = null; String name = null; String itemCode = null; String price = null; String quantity = null; String category = null; String image = null; HttpSession session = request.getSession(true); User user = (User) session.getAttribute("user"); if (user == null) { response.sendRedirect("login"); return; } // request.getServletContext().getRealPath("/uploads"); String path = request.getServletContext().getRealPath("/uploads"); System.out.println(path); if (ServletFileUpload.isMultipartContent(request)) { try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); // new File(path).mkdirs(); File directory = new File(path + File.separator + fileName); image = fileName; item.write(directory); } else { if ("name".equals(item.getFieldName())) { name = item.getString(); } else if ("id".equals(item.getFieldName())) { id = item.getString(); } else if ("itemCode".equals(item.getFieldName())) { itemCode = item.getString(); } else if ("price".equals(item.getFieldName())) { price = item.getString(); } else if ("quantity".equals(item.getFieldName())) { quantity = item.getString(); } else if ("category".equals(item.getFieldName())) { category = item.getString(); } } } //File uploaded successfully System.out.println("done"); } catch (Exception ex) { ex.printStackTrace(); } } boolean status = ItemRepository.editItem(name, itemCode, price, quantity, category, image, id); String message; System.out.println(status); if (status) { message = "Item saved successfully"; response.sendRedirect("dashboard"); } else { message = "Item not saved !!"; request.setAttribute("message", message); request.getRequestDispatcher("dashboard/addItem.jsp").forward(request, response); } }
From source file:fll.web.admin.UploadSubjectiveData.java
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response, final ServletContext application, final HttpSession session) throws IOException, ServletException { final StringBuilder message = new StringBuilder(); final File file = File.createTempFile("fll", null); Connection connection = null; try {// ww w. j ava 2 s. c o m // must be first to ensure the form parameters are set UploadProcessor.processUpload(request); final FileItem subjectiveFileItem = (FileItem) request.getAttribute("subjectiveFile"); subjectiveFileItem.write(file); final DataSource datasource = ApplicationAttributes.getDataSource(application); connection = datasource.getConnection(); saveSubjectiveData(file, Queries.getCurrentTournament(connection), ApplicationAttributes.getChallengeDescription(application), connection, application); message.append("<p id='success'><i>Subjective data uploaded successfully</i></p>"); } catch (final SAXParseException spe) { final String errorMessage = String.format( "Error parsing file line: %d column: %d%n Message: %s%n This may be caused by using the wrong version of the software attempting to parse a file that is not subjective data.", spe.getLineNumber(), spe.getColumnNumber(), spe.getMessage()); message.append("<p class='error'>" + errorMessage + "</p>"); LOGGER.error(errorMessage, spe); } catch (final SAXException se) { final String errorMessage = "The subjective scores file was found to be invalid, check that you are parsing a subjective scores file and not something else"; message.append("<p class='error'>" + errorMessage + "</p>"); LOGGER.error(errorMessage, se); } catch (final SQLException sqle) { message.append("<p class='error'>Error saving subjective data into the database: " + sqle.getMessage() + "</p>"); LOGGER.error(sqle, sqle); throw new RuntimeException("Error saving subjective data into the database", sqle); } catch (final ParseException e) { message.append( "<p class='error'>Error saving subjective data into the database: " + e.getMessage() + "</p>"); LOGGER.error(e, e); throw new RuntimeException("Error saving subjective data into the database", e); } catch (final FileUploadException e) { message.append("<p class='error'>Error processing subjective data upload: " + e.getMessage() + "</p>"); LOGGER.error(e, e); throw new RuntimeException("Error processing subjective data upload", e); } catch (final Exception e) { message.append( "<p class='error'>Error saving subjective data into the database: " + e.getMessage() + "</p>"); LOGGER.error(e, e); throw new RuntimeException("Error saving subjective data into the database", e); } finally { if (!file.delete()) { LOGGER.warn("Unable to delete file " + file.getAbsolutePath() + ", setting to delete on exit"); file.deleteOnExit(); } SQLFunctions.close(connection); } session.setAttribute("message", message.toString()); response.sendRedirect(response.encodeRedirectURL("index.jsp")); }