List of usage examples for org.apache.commons.fileupload FileItem getName
String getName();
From source file:com.gae.ImageUpServlet.java
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { //DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); //ReturnValue value = new ReturnValue(); MemoryFileItemFactory factory = new MemoryFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); resp.setContentType("image/jpeg"); ServletOutputStream out = resp.getOutputStream(); try {/*from w ww . j a v a 2 s .c o m*/ List<FileItem> list = upload.parseRequest(req); //FileItem list = upload.parseRequest(req); for (FileItem item : list) { if (!(item.isFormField())) { filename = item.getName(); if (filename != null && !"".equals(filename)) { int size = (int) item.getSize(); byte[] data = new byte[size]; InputStream in = item.getInputStream(); in.read(data); ImagesService imagesService = ImagesServiceFactory.getImagesService(); Image newImage = ImagesServiceFactory.makeImage(data); byte[] newImageData = newImage.getImageData(); //imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), filename.split(".")[0]); //imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), filename.split(".")[0]); out.write(newImageData); out.flush(); DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); Key key = KeyFactory.createKey(kind, skey); Blob blobImage = new Blob(newImageData); DirectBeans_textjson dbeans = new DirectBeans_textjson(); /* ?Date? */ //Entity entity = dbeans.setentity("add", kind, true, key, id, val); //ReturnValue value = dbeans.Called.setentity("add", kind, true, key, id, val); //Entity entity = value.entity; //DirectBeans.ReturnValue value = new DirectBeans.ReturnValue(); DirectBeans_textjson.entityVal eval = dbeans.setentity("add", kind, true, key, id, val); Entity entity = eval.entity; /* ?Date */ //for(int i=0; i<id.length; i++ ){ // if(id[i].equals("image")){ // //filetitle = val[i]; // //imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), val[i]); // } //} entity.setProperty("image", blobImage); Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd:HHmmss"); sdf.setTimeZone(TimeZone.getTimeZone("JST")); entity.setProperty("moddate", sdf.format(date)); //DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); ds.put(entity); out.println("? KEY:" + key); } } } } catch (FileUploadException e) { e.printStackTrace(); } finally { if (out != null) { out.close(); } } }
From source file:com.softwarementors.extjs.djn.demo.FormPostDemo.java
@DirectFormPostMethod public Result djnform_handleSubmit(Map<String, String> formParameters, Map<String, FileItem> fileFields) throws IOException { assert formParameters != null; assert fileFields != null; Result result = new Result(); StringBuilder fieldNamesAndValues = new StringBuilder("<p>Non file fields:</p>"); for (Map.Entry<String, String> entry : formParameters.entrySet()) { String fieldName = entry.getKey(); String value = entry.getValue(); StringBuilderUtils.appendAll(fieldNamesAndValues, "<b>", fieldName, "</b>='", value, "'<br>"); }// w w w . j a va 2 s . c o m fieldNamesAndValues.append("<p></p><p>FILE fields:</p>"); for (Map.Entry<String, FileItem> entry : fileFields.entrySet()) { String fieldName = entry.getKey(); FileItem fileItem = entry.getValue(); result.fileContents = IOUtils.toString(fileItem.getInputStream()); fileItem.getInputStream().close(); StringBuilderUtils.appendAll(fieldNamesAndValues, "<b>", fieldName, "</b>:"); boolean fileChosen = !fileItem.getName().equals(""); if (fileChosen) { StringBuilderUtils.appendAll(fieldNamesAndValues, " file=", fileItem.getName(), " (size=", Long.toString(fileItem.getSize()), ")"); } else { fieldNamesAndValues.append(" --no file was chosen--"); } } result.fieldNamesAndValues = fieldNamesAndValues.toString(); result.success = true; return result; }
From source file:ned.bcvs.admin.fileupload.ConstituencyFileUploadServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { // Check that we have a file upload request isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); if (!isMultipart) { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); return;/*from w w w. j a va 2s .co m*/ } DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File( "D:/glassfish12October/glassfish-4.0/glassfish4/" + "glassfish/domains/domain1/applications/temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\"))); } else { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); } fi.write(file); out.println("Uploaded Filename: " + fileName + "<br>"); } } //calling the ejb method to save constituency.csv file to data base out.println(upbean.fileDbUploader(filePath + fileName, "constituency")); out.println("</body>"); out.println("</html>"); } catch (Exception ex) { System.out.println(ex); } }
From source file:graphvis.webui.servlets.UploadServlet.java
/** * This method receives POST from the index.jsp page and uploads file, * converts into the correct format then places in the HDFS. */// w w w.j a va 2 s . c o m protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { response.setStatus(403); return; } File tempDirFileObject = new File(Configuration.tempDirectory); // Create/remove temp folder if (tempDirFileObject.exists()) { FileUtils.deleteDirectory(tempDirFileObject); } // (Re-)create temp directory tempDirFileObject.mkdir(); FileUtils.copyFile( new File(getServletContext() .getRealPath("giraph-1.1.0-SNAPSHOT-for-hadoop-2.2.0-jar-with-dependencies.jar")), new File(Configuration.tempDirectory + "/giraph-1.1.0-SNAPSHOT-for-hadoop-2.2.0-jar-with-dependencies.jar")); FileUtils.copyFile(new File(getServletContext().getRealPath("dist-graphvis.jar")), new File(Configuration.tempDirectory + "/dist-graphvis.jar")); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Sets the size threshold beyond which files are written directly to // disk. factory.setSizeThreshold(Configuration.MAX_MEMORY_SIZE); // Sets the directory used to temporarily store files that are larger // than the configured size threshold. We use temporary directory for // java factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(Configuration.MAX_REQUEST_SIZE); String fileName = ""; try { // Parse the request List<?> items = upload.parseRequest(request); Iterator<?> iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { fileName = new File(item.getName()).getName(); String filePath = Configuration.tempDirectory + File.separator + fileName; File uploadedFile = new File(filePath); System.out.println(filePath); // saves the file to upload directory try { item.write(uploadedFile); } catch (Exception ex) { throw new ServletException(ex); } } } String fullFilePath = Configuration.tempDirectory + File.separator + fileName; String extension = FilenameUtils.getExtension(fullFilePath); // Load Files intoHDFS // (This is where we do the parsing.) loadIntoHDFS(fullFilePath, extension); getServletContext().setAttribute("fileName", new File(fullFilePath).getName()); getServletContext().setAttribute("fileExtension", extension); // Displays fileUploaded.jsp page after upload finished getServletContext().getRequestDispatcher("/fileUploaded.jsp").forward(request, response); } catch (FileUploadException ex) { throw new ServletException(ex); } }
From source file:ned.bcvs.admin.fileupload.CandidateFileUploadServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { // Check that we have a file upload request isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); if (!isMultipart) { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); return;// w w w . ja v a 2 s . c o m } DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File( "D:/glassfish12October/glassfish-4.0/glassfish4/" + "glassfish/domains/domain1/applications/temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\"))); } else { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); } fi.write(file); out.println("Uploaded Filename: " + fileName + "<br>"); } } //calling the ejb method to save voter.csv file to data base out.println(upbean.fileDbUploader(filePath + fileName, "candidate")); out.println("</body>"); out.println("</html>"); } catch (Exception ex) { System.out.println(ex); } }
From source file:com.googlecode.psiprobe.controllers.deploy.UploadWarController.java
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { if (FileUpload.isMultipartContent(new ServletRequestContext(request))) { File tmpWar = null;/*ww w .j a v a 2s. c om*/ String contextName = null; boolean update = false; boolean compile = false; boolean discard = false; // // parse multipart request and extract the file // FileItemFactory factory = new DiskFileItemFactory(1048000, new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(-1); upload.setHeaderEncoding("UTF8"); try { for (Iterator it = upload.parseRequest(request).iterator(); it.hasNext();) { FileItem fi = (FileItem) it.next(); if (!fi.isFormField()) { if (fi.getName() != null && fi.getName().length() > 0) { tmpWar = new File(System.getProperty("java.io.tmpdir"), FilenameUtils.getName(fi.getName())); fi.write(tmpWar); } } else if ("context".equals(fi.getFieldName())) { contextName = fi.getString(); } else if ("update".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { update = true; } else if ("compile".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { compile = true; } else if ("discard".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { discard = true; } } } catch (Exception e) { logger.fatal("Could not process file upload", e); request.setAttribute("errorMessage", getMessageSourceAccessor() .getMessage("probe.src.deploy.war.uploadfailure", new Object[] { e.getMessage() })); if (tmpWar != null && tmpWar.exists()) { tmpWar.delete(); } tmpWar = null; } String errMsg = null; if (tmpWar != null) { try { if (tmpWar.getName().endsWith(".war")) { if (contextName == null || contextName.length() == 0) { String warFileName = tmpWar.getName().replaceAll("\\.war$", ""); contextName = "/" + warFileName; } contextName = getContainerWrapper().getTomcatContainer().formatContextName(contextName); // // pass the name of the newly deployed context to the presentation layer // using this name the presentation layer can render a url to view compilation details // String visibleContextName = "".equals(contextName) ? "/" : contextName; request.setAttribute("contextName", visibleContextName); if (update && getContainerWrapper().getTomcatContainer().findContext(contextName) != null) { logger.debug("updating " + contextName + ": removing the old copy"); getContainerWrapper().getTomcatContainer().remove(contextName); } if (getContainerWrapper().getTomcatContainer().findContext(contextName) == null) { // // move the .war to tomcat application base dir // String destWarFilename = getContainerWrapper().getTomcatContainer() .formatContextFilename(contextName); File destWar = new File(getContainerWrapper().getTomcatContainer().getAppBase(), destWarFilename + ".war"); FileUtils.moveFile(tmpWar, destWar); // // let Tomcat know that the file is there // getContainerWrapper().getTomcatContainer().installWar(contextName, new URL("jar:" + destWar.toURI().toURL().toString() + "!/")); Context ctx = getContainerWrapper().getTomcatContainer().findContext(contextName); if (ctx == null) { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notinstalled", new Object[] { visibleContextName }); } else { request.setAttribute("success", Boolean.TRUE); if (discard) { getContainerWrapper().getTomcatContainer().discardWorkDir(ctx); } if (compile) { Summary summary = new Summary(); summary.setName(ctx.getName()); getContainerWrapper().getTomcatContainer().listContextJsps(ctx, summary, true); request.getSession(true).setAttribute(DisplayJspController.SUMMARY_ATTRIBUTE, summary); request.setAttribute("compileSuccess", Boolean.TRUE); } } } else { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.alreadyExists", new Object[] { visibleContextName }); } } else { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notWar.failure"); } } catch (Exception e) { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.failure", new Object[] { e.getMessage() }); logger.error("Tomcat throw an exception when trying to deploy", e); } finally { if (errMsg != null) { request.setAttribute("errorMessage", errMsg); } tmpWar.delete(); } } } return new ModelAndView(new InternalResourceView(getViewName())); }
From source file:cn.hhh.myandroidserver.response.AndServerUploadHandler.java
/** * ??SD?/*from www.jav a2s . c o m*/ * * @param request {@link HttpRequest}. * @param uploadDir ? * @throws Exception ??? */ private void processFileUpload(HttpRequest request, File uploadDir) throws Exception { FileItemFactory factory = new DiskFileItemFactory(1024 * 1024, uploadDir); HttpServFileUpload fileUpload = new HttpServFileUpload(factory); // ???handlerUI fileUpload.setProgressListener(new AndWebProgressListener()); List<FileItem> fileItems = fileUpload.parseRequest(new HttpServRequestContext(request)); for (FileItem fileItem : fileItems) { if (!fileItem.isFormField()) { // ? // fileItem.getContentType() File uploadedFile = new File(uploadDir, fileItem.getName()); // ? fileItem.write(uploadedFile); } } }
From source file:fr.paris.lutece.plugins.asynchronousupload.service.AbstractAsynchronousUploadHandler.java
/** * {@inheritDoc}//w w w. j a v a2 s . c o m */ @Override public void addFilesUploadedSynchronously(HttpServletRequest request, String strFieldName) { if (request instanceof MultipartHttpServletRequest && hasAddFileFlag(request, strFieldName)) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; List<FileItem> listFileItem = multipartRequest.getFileList(strFieldName); if ((listFileItem != null) && (listFileItem.size() > 0)) { for (FileItem fileItem : listFileItem) { if ((fileItem.getSize() > 0L) && StringUtils.isNotEmpty(fileItem.getName())) { addFileItemToUploadedFilesList(fileItem, strFieldName, request); } } } } }
From source file:ned.bcvs.fileupload.ElectionPartyFileUploadServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { // Check that we have a file upload request isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); if (!isMultipart) { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); return;/*from w ww . ja v a2s .co m*/ } DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File( "D:/glassfish12October/glassfish-4.0/glassfish4/" + "glassfish/domains/domain1/applications/temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\"))); } else { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); } fi.write(file); out.println("Uploaded Filename: " + fileName + "<br>"); } } //calling the ejb method to save voter.csv file to data base out.println(upbean.fileDbUploader(filePath + fileName, "electionparty")); out.println("</body>"); out.println("</html>"); } catch (Exception ex) { System.out.println(ex); } }
From source file:com.ephesoft.gxt.uploadbatch.server.UploadBatchImageServlet.java
private void uploadFile(HttpServletRequest req, HttpServletResponse resp, BatchSchemaService batchSchemaService, String currentBatchUploadFolderName) throws IOException { PrintWriter printWriter = resp.getWriter(); File tempFile = null;/*from w w w . j a va2 s.com*/ InputStream instream = null; OutputStream out = null; String uploadBatchFolderPath = batchSchemaService.getUploadBatchFolder(); String uploadFileName = ""; if (ServletFileUpload.isMultipartContent(req)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); uploadFileName = ""; String uploadFilePath = ""; List<FileItem> items; try { items = upload.parseRequest(req); for (FileItem item : items) { if (!item.isFormField()) { // && "uploadFile".equals(item.getFieldName())) { uploadFileName = item.getName(); if (uploadFileName != null) { uploadFileName = uploadFileName .substring(uploadFileName.lastIndexOf(File.separator) + 1); } uploadFilePath = uploadBatchFolderPath + File.separator + currentBatchUploadFolderName + File.separator + uploadFileName; try { instream = item.getInputStream(); tempFile = new File(uploadFilePath); out = new FileOutputStream(tempFile); byte buf[] = new byte[1024]; int len; while ((len = instream.read(buf)) > 0) { out.write(buf, 0, len); } } catch (FileNotFoundException e) { log.error("Unable to create the upload folder." + e, e); printWriter.write("Unable to create the upload folder.Please try again."); tempFile.delete(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "unable to upload. please see server logs for more details."); } catch (IOException e) { log.error("Unable to read the file." + e, e); printWriter.write("Unable to read the file.Please try again."); tempFile.delete(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "unable to upload. please see server logs for more details."); } finally { if (out != null) { out.close(); } if (instream != null) { instream.close(); } } } } } catch (FileUploadException e) { log.error("Unable to read the form contents." + e, e); printWriter.write("Unable to read the form contents.Please try again."); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "unable to upload. please see server logs for more details."); } } else { log.error("Request contents type is not supported."); printWriter.write("Request contents type is not supported."); } printWriter.write("currentBatchUploadFolderName:" + currentBatchUploadFolderName); printWriter.append("|"); printWriter.append("fileName:").append(uploadFileName); printWriter.append("|"); printWriter.flush(); }