List of usage examples for org.apache.commons.fileupload FileItem getName
String getName();
From source file:com.zlfun.framework.excel.ExcelUtils.java
public static <T> List<T> httpInput(HttpServletRequest request, Class<T> clazz) { List<T> result = new ArrayList<T>(); //?? //www.j a v a2 s .c om DiskFileItemFactory factory = new DiskFileItemFactory(); //?? String path = request.getSession().getServletContext().getRealPath("/"); factory.setRepository(new File(path)); // ?? factory.setSizeThreshold(1024 * 1024); ServletFileUpload upload = new ServletFileUpload(factory); try { //? List<FileItem> list = (List<FileItem>) upload.parseRequest(request); for (FileItem item : list) { //???? String name = item.getFieldName(); //? ?? ? if (item.isFormField()) { //? ?????? String value = item.getString(); request.setAttribute(name, value); } //? ?? else { /** * ?? ?? */ //??? String value = item.getName(); //???? fill(clazz, result, value, item.getInputStream()); //?? } } } catch (FileUploadException ex) { // TODO Auto-generated catch block excel=null; Logger.getLogger(ExcelUtils.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ExcelUtils.class.getName()).log(Level.SEVERE, null, ex); } return result; }
From source file:com.silverpeas.attachment.servlets.DragAndDrop.java
/** * Method declaration/*from www . j av a 2s .co m*/ * @param req * @param res * @throws IOException * @throws ServletException * @see */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_ENTER_METHOD"); if (!FileUploadUtil.isRequestMultipart(req)) { res.getOutputStream().println("SUCCESS"); return; } ResourceLocator settings = new ResourceLocator("com.stratelia.webactiv.util.attachment.Attachment", ""); boolean actifyPublisherEnable = settings.getBoolean("ActifyPublisherEnable", false); try { req.setCharacterEncoding("UTF-8"); String componentId = req.getParameter("ComponentId"); SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "componentId = " + componentId); String id = req.getParameter("PubId"); SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "id = " + id); String userId = req.getParameter("UserId"); SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "userId = " + userId); String context = req.getParameter("Context"); boolean bIndexIt = StringUtil.getBooleanValue(req.getParameter("IndexIt")); List<FileItem> items = FileUploadUtil.parseRequest(req); for (FileItem item : items) { SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "item = " + item.getFieldName()); SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "item = " + item.getName() + "; " + item.getString("UTF-8")); if (!item.isFormField()) { String fileName = item.getName(); if (fileName != null) { String physicalName = saveFileOnDisk(item, componentId, context); String mimeType = AttachmentController.getMimeType(fileName); long size = item.getSize(); SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "item size = " + size); // create AttachmentDetail Object AttachmentDetail attachment = new AttachmentDetail( new AttachmentPK(null, "useless", componentId), physicalName, fileName, null, mimeType, size, context, new Date(), new AttachmentPK(id, "useless", componentId)); attachment.setAuthor(userId); try { AttachmentController.createAttachment(attachment, bIndexIt); } catch (Exception e) { // storing data into DB failed, delete file just added on disk deleteFileOnDisk(physicalName, componentId, context); throw e; } // Specific case: 3d file to convert by Actify Publisher if (actifyPublisherEnable) { String extensions = settings.getString("Actify3dFiles"); StringTokenizer tokenizer = new StringTokenizer(extensions, ","); // 3d native file ? boolean fileForActify = false; SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "nb tokenizer =" + tokenizer.countTokens()); String type = FileRepositoryManager.getFileExtension(fileName); while (tokenizer.hasMoreTokens() && !fileForActify) { String extension = tokenizer.nextToken(); fileForActify = type.equalsIgnoreCase(extension); } if (fileForActify) { String dirDestName = "a_" + componentId + "_" + id; String actifyWorkingPath = settings.getString("ActifyPathSource") + File.separatorChar + dirDestName; String destPath = FileRepositoryManager.getTemporaryPath() + actifyWorkingPath; if (!new File(destPath).exists()) { FileRepositoryManager.createGlobalTempPath(actifyWorkingPath); } String normalizedFileName = FilenameUtils.normalize(fileName); if (normalizedFileName == null) { normalizedFileName = FilenameUtils.getName(fileName); } String destFile = FileRepositoryManager.getTemporaryPath() + actifyWorkingPath + File.separatorChar + normalizedFileName; FileRepositoryManager .copyFile(AttachmentController.createPath(componentId, "Images") + File.separatorChar + physicalName, destFile); } } } } } } catch (Exception e) { SilverTrace.error("attachment", "DragAndDrop.doPost", "ERREUR", e); res.getOutputStream().println("ERROR"); return; } res.getOutputStream().println("SUCCESS"); }
From source file:it.eng.spagobi.engines.talend.services.JobUploadService.java
private String[] processUploadedFile(FileItem item, JobDeploymentDescriptor jobDeploymentDescriptor) throws ZipException, IOException, SpagoBIEngineException { String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); if (fieldName.equalsIgnoreCase("deploymentDescriptor")) return null; RuntimeRepository runtimeRepository = TalendEngine.getRuntimeRepository(); File jobsDir = new File(runtimeRepository.getRootDir(), jobDeploymentDescriptor.getLanguage().toLowerCase()); File projectDir = new File(jobsDir, jobDeploymentDescriptor.getProject()); File tmpDir = new File(projectDir, "tmp"); if (!tmpDir.exists()) tmpDir.mkdirs();//w w w. j a va 2 s . c om File uploadedFile = new File(tmpDir, fileName); try { item.write(uploadedFile); } catch (Exception e) { e.printStackTrace(); } String[] dirNames = ZipUtils.getDirectoryNameByLevel(new ZipFile(uploadedFile), 2); List dirNameList = new ArrayList(); for (int i = 0; i < dirNames.length; i++) { if (!dirNames[i].equalsIgnoreCase("lib")) dirNameList.add(dirNames[i]); } String[] jobNames = (String[]) dirNameList.toArray(new String[0]); runtimeRepository.deployJob(jobDeploymentDescriptor, new ZipFile(uploadedFile)); uploadedFile.delete(); tmpDir.delete(); return jobNames; }
From source file:com.intelligentz.appointmentz.controllers.addSession.java
@SuppressWarnings("Since15") @Override// w ww. j a v a 2 s . c o m public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { String room_id = null; String doctor_id = null; String start_time = null; String date_picked = null; ArrayList<SessonCustomer> sessonCustomers = new ArrayList<>(); 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(filePath + "temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); // Parse the request to get file items. List fileItems = upload.parseRequest(req); // Process the uploaded file items Iterator i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if (fileName.lastIndexOf("\\") >= 0) { filePath = filePath + fileName.substring(fileName.lastIndexOf("\\")); file = new File(filePath); } else { filePath = filePath + fileName.substring(fileName.lastIndexOf("\\") + 1); file = new File(filePath); } fi.write(file); Files.lines(Paths.get(filePath)).forEach((line) -> { String[] cust = line.split(","); sessonCustomers.add(new SessonCustomer(cust[0].trim(), Integer.parseInt(cust[1].trim()))); }); } else { if (fi.getFieldName().equals("room_id")) room_id = fi.getString(); else if (fi.getFieldName().equals("doctor_id")) doctor_id = fi.getString(); else if (fi.getFieldName().equals("start_time")) start_time = fi.getString(); else if (fi.getFieldName().equals("date_picked")) date_picked = fi.getString(); } } con = new connectToDB(); if (con.connect()) { Connection connection = con.getConnection(); Class.forName("com.mysql.jdbc.Driver"); Statement stmt = connection.createStatement(); String SQL, SQL1, SQL2; SQL1 = "insert into db_bro.session ( doctor_id, room_id, date, start_time) VALUES (?,?,?,?)"; PreparedStatement preparedStmt = connection.prepareStatement(SQL1); preparedStmt.setString(1, doctor_id); preparedStmt.setString(2, room_id); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH:mm"); try { java.util.Date d = formatter.parse(date_picked + "-" + start_time); Date d_sql = new Date(d.getTime()); java.util.Date N = new java.util.Date(); if (N.compareTo(d) > 0) { res.sendRedirect("./error.jsp?error=Invalid Date!"); } //String [] T = start_time.split(":"); //Time t = Time.valueOf(start_time); //Time t = new Time(Integer.parseInt(T[0]),Integer.parseInt(T[1]),0); //java.sql.Time t_sql = new java.sql.Date(d.getTime()); preparedStmt.setString(4, start_time + ":00"); preparedStmt.setDate(3, d_sql); } catch (ParseException e) { displayMessage(res, "Invalid Date!" + e.getLocalizedMessage()); } // execute the preparedstatement preparedStmt.execute(); SQL = "select * from db_bro.session ORDER BY session_id DESC limit 1"; ResultSet rs = stmt.executeQuery(SQL); boolean check = false; while (rs.next()) { String db_doctor_id = rs.getString("doctor_id"); String db_date_picked = rs.getString("date"); String db_start_time = rs.getString("start_time"); String db_room_id = rs.getString("room_id"); if ((doctor_id == null ? db_doctor_id == null : doctor_id.equals(db_doctor_id)) && (start_time == null ? db_start_time == null : (start_time + ":00").equals(db_start_time)) && (room_id == null ? db_room_id == null : room_id.equals(db_room_id)) && (date_picked == null ? db_date_picked == null : date_picked.equals(db_date_picked))) { check = true; //displayMessage(res,"Authentication Success!"); SQL2 = "insert into db_bro.session_customers ( session_id, mobile, appointment_num) VALUES (?,?,?)"; for (SessonCustomer sessonCustomer : sessonCustomers) { preparedStmt = connection.prepareStatement(SQL2); preparedStmt.setString(1, rs.getString("session_id")); preparedStmt.setString(2, sessonCustomer.getMobile()); preparedStmt.setInt(3, sessonCustomer.getAppointment_num()); preparedStmt.execute(); } try { connection.close(); } catch (SQLException e) { displayMessage(res, "SQLException"); } res.sendRedirect("./home"); } } if (!check) { try { connection.close(); } catch (SQLException e) { displayMessage(res, "SQLException"); } displayMessage(res, "SQL query Failed!"); } } else { con.showErrormessage(res); } /*res.setContentType("text/html");//setting the content type PrintWriter pw=res.getWriter();//get the stream to write the data //writing html in the stream pw.println("<html><body>"); pw.println("Welcome to servlet: "+username); pw.println("</body></html>"); pw.close();//closing the stream */ } catch (Exception ex) { Logger.getLogger(authenticate.class.getName()).log(Level.SEVERE, null, ex); displayMessage(res, "Error!" + ex.getLocalizedMessage()); } }
From source file:com.tasktop.c2c.server.tasks.web.service.AttachmentUploadController.java
@RequestMapping(value = "", method = RequestMethod.POST) public void upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, TextHtmlContentExceptionWrapper { try {/*from w ww . ja va2 s . co m*/ FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<Attachment> attachments = new ArrayList<Attachment>(); Map<String, String> formValues = new HashMap<String, String>(); try { List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { formValues.put(item.getFieldName(), item.getString()); } else { Attachment attachment = new Attachment(); attachment.setAttachmentData(readInputStream(item.getInputStream())); attachment.setFilename(item.getName()); attachment.setMimeType(item.getContentType()); attachments.add(attachment); } } } catch (FileUploadException e) { e.printStackTrace(); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); // FIXME better code return; } for (int i = 0; i < attachments.size(); i++) { String description = formValues .get(AttachmentUploadUtil.ATTACHMENT_DESCRIPTION_FORM_NAME_PREFIX + i); if (description == null) { throw new IllegalArgumentException( "Missing description " + i + 1 + " of " + attachments.size()); } attachments.get(0).setDescription(description); } TaskHandle taskHandle = getTaskHandle(formValues); UploadResult result = doUpload(response, attachments, taskHandle); response.setContentType("text/html"); response.getWriter() .write(jsonMapper.writeValueAsString(Collections.singletonMap("uploadResult", result))); } catch (Exception e) { throw new TextHtmlContentExceptionWrapper(e.getMessage(), e); } }
From source file:adminShop.registraProducto.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w ww .java2s . com * * @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 { String message = "Error"; boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items; HashMap hm = new HashMap(); ArrayList<Imagen> imgs = new ArrayList<>(); Producto prod = new Producto(); Imagen img = null; try { items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); hm.put(name, value); } else { img = new Imagen(); String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeBytes = item.getSize(); File file = new File("/home/gama/Escritorio/adoo/" + fileName + ".jpg"); item.write(file); Path path = Paths.get("/home/gama/Escritorio/adoo/" + fileName + ".jpg"); byte[] data = Files.readAllBytes(path); byte[] encode = org.apache.commons.codec.binary.Base64.encodeBase64(data); img.setUrl(new javax.sql.rowset.serial.SerialBlob(encode)); imgs.add(img); //file.delete(); } } prod.setNombre((String) hm.get("nombre")); prod.setProdNum((String) hm.get("prodNum")); prod.setDesc((String) hm.get("desc")); prod.setIva(Double.parseDouble((String) hm.get("iva"))); prod.setPrecio(Double.parseDouble((String) hm.get("precio"))); prod.setPiezas(Integer.parseInt((String) hm.get("piezas"))); prod.setEstatus("A"); prod.setImagenes(imgs); ProductoDAO prodDAO = new ProductoDAO(); if (prodDAO.registraProducto(prod)) { message = "Exito"; } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } response.sendRedirect("index.jsp"); }
From source file:com.scooterframework.web.controller.ScooterRequestFilter.java
protected String requestInfo(boolean skipStatic, HttpServletRequest request) { String method = getRequestMethod(request); String requestPath = getRequestPath(request); String requestPathKey = RequestInfo.generateRequestKey(requestPath, method); String s = requestPathKey;// www . j a v a2 s . c o m String queryString = request.getQueryString(); if (queryString != null) s += "?" + queryString; CurrentThreadCacheClient.cacheHttpMethod(method); CurrentThreadCacheClient.cacheRequestPath(requestPath); CurrentThreadCacheClient.cacheRequestPathKey(requestPathKey); if (skipStatic) return s; //request header Properties headers = new Properties(); Enumeration<?> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = (String) headerNames.nextElement(); String value = request.getHeader(name); if (value != null) headers.setProperty(name, value); } CurrentThreadCache.set(Constants.REQUEST_HEADER, headers); if (isLocalRequest(request)) { CurrentThreadCache.set(Constants.LOCAL_REQUEST, Constants.VALUE_FOR_LOCAL_REQUEST); } if (isFileUploadRequest(request)) { CurrentThreadCache.set(Constants.FILE_UPLOAD_REQUEST, Constants.VALUE_FOR_FILE_UPLOAD_REQUEST); try { List<FileItem> files = new ArrayList<FileItem>(); ServletFileUpload fileUpload = EnvConfig.getInstance().getServletFileUpload(); List<?> items = fileUpload.parseRequest(request); for (Object fi : items) { FileItem item = (FileItem) fi; if (item.isFormField()) { ActionControl.storeToRequest(item.getFieldName(), item.getString()); } else if (!item.isFormField() && !"".equals(item.getName())) { files.add(item); } } CurrentThreadCache.set(Constants.FILE_UPLOAD_REQUEST_FILES, files); } catch (Exception ex) { CurrentThreadCacheClient.storeError(new FileUploadException(ex)); } } return s; }
From source file:com.silverpeas.form.AbstractForm.java
/** * Is the form is empty? A form is empty if all of its fields aren't valued (no data associated * with them)./* ww w.j a v a 2 s . c o m*/ * @param items the items embbeding multipart data in the form. * @param record the record of data. * @param pagesContext the page context. * @return true if one of the form field has no data. */ @Override public boolean isEmpty(List<FileItem> items, DataRecord record, PagesContext pagesContext) { boolean isEmpty = true; for (FieldTemplate fieldTemplate : fieldTemplates) { FieldDisplayer fieldDisplayer = null; if (fieldTemplate != null) { String fieldType = fieldTemplate.getTypeName(); String fieldDisplayerName = fieldTemplate.getDisplayerName(); try { if (!StringUtil.isDefined(fieldDisplayerName)) { fieldDisplayerName = getTypeManager().getDisplayerName(fieldType); } fieldDisplayer = getTypeManager().getDisplayer(fieldType, fieldDisplayerName); if (fieldDisplayer != null) { String itemName = fieldTemplate.getFieldName(); FileItem item = getParameter(items, itemName); if (item != null && !item.isFormField() && StringUtil.isDefined(item.getName())) { isEmpty = false; } else { String itemValue = getParameterValue(items, itemName, pagesContext.getEncoding()); isEmpty = !StringUtil.isDefined(itemValue); } } } catch (Exception e) { SilverTrace.error("form", "AbstractForm.isEmpty", "form.EXP_UNKNOWN_FIELD", null, e); } } if (!isEmpty) { break; } } return isEmpty; }
From source file:com.zlk.fckeditor.Dispatcher.java
/** * Called by the connector servlet to handle a {@code POST} request. In * particular, it handles the {@link Command#FILE_UPLOAD FileUpload} and * {@link Command#QUICK_UPLOAD QuickUpload} commands. * /*w ww . j a v a 2 s . c om*/ * @param request * the current request instance * @return the upload response instance associated with this request */ UploadResponse doPost(final HttpServletRequest request) { logger.debug("Entering Dispatcher#doPost"); Context context = ThreadLocalData.getContext(); context.logBaseParameters(); UploadResponse uploadResponse = null; // check permissions for user actions if (!RequestCycleHandler.isFileUploadEnabled(request)) uploadResponse = UploadResponse.getFileUploadDisabledError(); // check parameters else if (!Command.isValidForPost(context.getCommandStr())) uploadResponse = UploadResponse.getInvalidCommandError(); else if (!ResourceType.isValidType(context.getTypeStr())) uploadResponse = UploadResponse.getInvalidResourceTypeError(); else if (!UtilsFile.isValidPath(context.getCurrentFolderStr())) uploadResponse = UploadResponse.getInvalidCurrentFolderError(); else { // call the Connector#fileUpload ResourceType type = context.getDefaultResourceType(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> items = upload.parseRequest(request); // We upload just one file at the same time FileItem uplFile = items.get(0); // Some browsers transfer the entire source path not just the // filename String fileName = FilenameUtils.getName(uplFile.getName()); logger.debug("Parameter NewFile: {}", fileName); // ?? if (uplFile.getSize() > 1024 * 1024 * 50) {//50M // ? uploadResponse = new UploadResponse(204); } else { //??uuid? String extension = FilenameUtils.getExtension(fileName); fileName = UUID.randomUUID().toString() + "." + extension; /* String path=request.getSession().getServletContext().getRealPath("/")+"userfiles/"; fileName = makeFileName(path+"/"+type.getPath(), fileName);*/ logger.debug("Change FileName to UUID: {} (by zhoulukang)", fileName); // check the extension if (type.isDeniedExtension(FilenameUtils.getExtension(fileName))) uploadResponse = UploadResponse.getInvalidFileTypeError(); // Secure image check (can't be done if QuickUpload) else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads() && !UtilsFile.isImage(uplFile.getInputStream())) { uploadResponse = UploadResponse.getInvalidFileTypeError(); } else { String sanitizedFileName = UtilsFile.sanitizeFileName(fileName); logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName); String newFileName = connector.fileUpload(type, context.getCurrentFolderStr(), sanitizedFileName, uplFile.getInputStream()); String fileUrl = UtilsResponse.fileUrl(RequestCycleHandler.getUserFilesPath(request), type, context.getCurrentFolderStr(), newFileName); if (sanitizedFileName.equals(newFileName)) uploadResponse = UploadResponse.getOK(fileUrl); else { uploadResponse = UploadResponse.getFileRenamedWarning(fileUrl, newFileName); logger.debug("Parameter NewFile (renamed): {}", newFileName); } } uplFile.delete(); } } catch (InvalidCurrentFolderException e) { uploadResponse = UploadResponse.getInvalidCurrentFolderError(); } catch (WriteException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } catch (IOException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } catch (FileUploadException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } } logger.debug("Exiting Dispatcher#doPost"); return uploadResponse; }