List of usage examples for org.apache.commons.fileupload FileItem write
void write(File file) throws Exception;
From source file:com.bmth.MyServlet.UploadServlet.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); boolean isMultipart = ServletFileUpload.isMultipartContent(request); HttpSession session = request.getSession(); Account account = (Account) session.getAttribute("account"); Register re = new Register(); User user = re.getUserById(account.getUserId()); // process only if it is multipart content String status = "aaa"; String category = "other"; if (isMultipart) { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); try {/*from ww w . j a v a 2 s. c o m*/ // Parse the request List<FileItem> multiparts = upload.parseRequest(request); ImageDAO img = new ImageDAO(); String imgId = user.getUserId() + "" + (img.getAllImageUserId(user.getUserId()).size() + 1); int imageId = Integer.parseInt(imgId); Image image = new Image(); image.setImgId(imageId); image.setUserId(user.getUserId()); image.setPoint(0f); image.setImgDate(Calendar.getInstance().getTimeInMillis()); for (FileItem item : multiparts) { if (!item.isFormField()) { String contentType = item.getContentType(); String[] ext = contentType.split("/"); String fileName = UPLOAD_DIRECTORY + File.separator + user.getUserId() + "_" + imgId; File file = new File(fileName); item.write(file); image.setImgUrl("http://localhost:8080/Image/" + file.getName()); } else { String fieldName = item.getFieldName(); if (fieldName.equals("status")) { image.setImgDescribe(item.getString()); } if (fieldName.equals("optionsRadios")) { image.setTheme(theme(item.getString())); } } } img.AddImage(image); } catch (Exception e) { e.printStackTrace(); } } String json = "{\"message\": \"success\"}"; response.getWriter().write(json); }
From source file:com.intranet.intr.proveedores.ProvController.java
@RequestMapping(value = "enviarPresupuestoA.htm", method = RequestMethod.POST) public String enviarPresupuestoA_post(@ModelAttribute("provPresupAdj") prov_presup_adj provPresupAdj, BindingResult result, HttpServletRequest request) { String mensaje = ""; try {// w w w . j av a 2 s . c om //MultipartFile multipart = c.getArchivo(); System.out.println("olaEnviarMAILS"); String ubicacionArchivo = "C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\archivosProveedores"; //File file=new File(ubicacionArchivo,multipart.getOriginalFilename()); //String ubicacionArchivo="C:\\"; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> partes = upload.parseRequest(request); for (FileItem item : partes) { System.out.println("NOMBRE FOTO: " + item.getContentType()); File file = new File(ubicacionArchivo, item.getName()); item.write(file); prov_presup_adj pp = new prov_presup_adj(); pp.setNombre(item.getName()); pp.setTipo(item.getContentType()); arc.add(pp); System.out.println("img" + item.getName()); } //c.setImagenes(arc); } catch (Exception ex) { } return "redirect:enviarPresupuesto.htm"; }
From source file:controller.insertProduct.java
private void insertProduct(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); String productType = null;/* w w w .ja va 2s . com*/ String resolution = null; String hdmi = null; String usb = null; String model = null; String size = null; String warranty = null; String productName = null; int price = 0; String description = null; Integer quantity = null; String produceID = null; String image = null; String uploadDirectory = "/Product/Images"; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(MEMORY_THRESHOLD); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(MAX_FILE_SIZE); upload.setSizeMax(MAX_REQUEST_SIZE); File uploadDir; File storeFile; try { @SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(request); if (formItems != null && formItems.size() > 0) { for (FileItem item : formItems) { if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); String filePath = uploadDirectory + File.separator + fileName; storeFile = new File(filePath); item.write(storeFile); image = produceID + "/" + fileName; System.out.println(storeFile.getPath()); } else { switch (item.getFieldName()) { case "productName": productName = item.getString("UTF-8"); break; case "produceID": { produceID = item.getString("UTF-8"); uploadDir = new File(uploadPath + uploadDirectory + "/" + produceID); if (!uploadDir.exists()) { uploadDir.mkdir(); } uploadDirectory = uploadPath + uploadDirectory + "/" + produceID; break; } case "price": price = (Integer.parseInt(item.getString("UTF-8"))); break; case "quantity": quantity = (Integer.parseInt(item.getString("UTF-8"))); break; case "productType": productType = item.getString("UTF-8"); break; case "resolution": resolution = item.getString("UTF-8"); break; case "hdmi": hdmi = item.getString("UTF-8"); break; case "usb": usb = item.getString("UTF-8"); break; case "Model": model = item.getString("UTF-8"); break; case "size": size = item.getString("UTF-8"); break; case "warranty": warranty = item.getString("UTF-8"); break; case "description": { description = item.getString("UTF-8"); System.out.println(description); break; } } } } } } catch (Exception ex) { System.out.println(ex); } @SuppressWarnings("null") ProductInfo prinfo = new ProductInfo(productType, resolution, hdmi, usb, model, size, warranty); Products product = new Products(productName, price, description, quantity, image, prinfo, produceID); if (ProductsDAO.insertProduct(product)) { out.print( "<center><b><font color='red'>thm thnh cng! </font> <a href = './WEB/admin/showProduct.jsp'>quay v?</a></b></center>"); } else { out.print( "<center><b><font color='red'>Thm tht bi! </font> <a href = './WEB/admin/showProduct.jsp'>quay v?</a></b></center>"); } }
From source file:com.sapuraglobal.hrms.servlet.UploadEmp.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from ww w . j a v a 2 s . c om*/ * * @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"); String action = request.getParameter("action"); System.out.println("action: " + action); if (action == null || action.isEmpty()) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); //PriceDAO priceDAO = new PriceDAO(); try { List<FileItem> fields = upload.parseRequest(request); //out.println("Number of fields: " + fields.size() + "<br/><br/>"); Iterator<FileItem> it = fields.iterator(); while (it.hasNext()) { FileItem fileItem = it.next(); //store in webserver. String fileName = fileItem.getName(); if (fileName != null) { File file = new File(fileName); fileItem.write(file); System.out.println("File successfully saved as " + file.getAbsolutePath()); //process file Reader in = new FileReader(file.getAbsolutePath()); Iterable<CSVRecord> records = CSVFormat.EXCEL.withHeader().parse(in); for (CSVRecord record : records) { String name = record.get("<name>"); String login = record.get("<login>"); String title = record.get("<title>"); String email = record.get("<email>"); String role = record.get("<role>"); String dept = record.get("<department>"); String joinDate = record.get("<joinDate>"); String probDate = record.get("<probDate>"); String annLeaveEnt = record.get("<leave_entitlement>"); String annBal = record.get("<leave_bal>"); String annMax = record.get("<leave_max>"); String annCF = record.get("<leave_cf>"); String med = record.get("<med_taken>"); String oil = record.get("<oil_taken>"); String unpaid = record.get("<unpaid_taken>"); String child = record.get("<child_bal>"); TitleDTO titleDto = titleBean.getTitleByName(title); RoleDTO roleDto = accessBean.getRole(role); DeptDTO deptDto = deptBean.getDepartment(dept); //create the user first UserDTO user = new UserDTO(); user.setName(name); user.setLogin(login); user.setTitle(titleDto); user.setEmail(email); user.setDateJoin(Utility.format(joinDate, "dd/MM/yyyy")); user.setProbationDue(Utility.format(probDate, "dd/MM/yyyy")); //store in user table. userBean.createUser(user); //assign role userBean.assignRole(user, roleDto); //assign dept deptBean.assignEmployee(user, deptDto); //leave ent LeaveTypeDTO lvtypeDTO = leaveBean.getLeaveType("Annual"); LeaveEntDTO annualentDTO = new LeaveEntDTO(); annualentDTO.setCurrent(Double.parseDouble(annLeaveEnt)); annualentDTO.setBalance(Double.parseDouble(annBal)); annualentDTO.setMax(Double.parseDouble(annMax)); annualentDTO.setCarriedOver(Double.parseDouble(annCF)); annualentDTO.setLeaveType(lvtypeDTO); //assign annual leave annualentDTO.setUser(user); leaveBean.addLeaveEnt(annualentDTO); //medical ent LeaveTypeDTO medTypeDTO = leaveBean.getLeaveType("Medical Leave"); LeaveEntDTO medentDTO = new LeaveEntDTO(); medentDTO.setBalance(medTypeDTO.getDays() - Double.parseDouble(med)); medentDTO.setCurrent(medTypeDTO.getDays()); medentDTO.setUser(user); medentDTO.setLeaveType(medTypeDTO); leaveBean.addLeaveEnt(medentDTO); //oil ent LeaveTypeDTO oilTypeDTO = leaveBean.getLeaveType("Off-in-Lieu"); LeaveEntDTO oilentDTO = new LeaveEntDTO(); oilentDTO.setBalance(oilTypeDTO.getDays() - Double.parseDouble(oil)); oilentDTO.setCurrent(0); oilentDTO.setUser(user); oilentDTO.setLeaveType(oilTypeDTO); leaveBean.addLeaveEnt(oilentDTO); //unpaid LeaveTypeDTO unpaidTypeDTO = leaveBean.getLeaveType("Unpaid"); LeaveEntDTO unpaidentDTO = new LeaveEntDTO(); unpaidentDTO.setBalance(unpaidTypeDTO.getDays() - Double.parseDouble(unpaid)); unpaidentDTO.setCurrent(0); unpaidentDTO.setUser(user); unpaidentDTO.setLeaveType(unpaidTypeDTO); leaveBean.addLeaveEnt(unpaidentDTO); //child LeaveTypeDTO childTypeDTO = leaveBean.getLeaveType("Child Care"); double cur = childTypeDTO.getDays(); LeaveEntDTO childentDTO = new LeaveEntDTO(); childentDTO.setBalance(cur - Double.parseDouble(child)); childentDTO.setCurrent(cur); childentDTO.setUser(user); childentDTO.setLeaveType(childTypeDTO); leaveBean.addLeaveEnt(childentDTO); } /* if (stockPrices.size() > 0) { priceDAO.OpenConnection(); priceDAO.updateStockPrice(stockPrices); } */ } } } catch (Exception e) { e.printStackTrace(); } finally { //priceDAO.CloseConnection(); RequestDispatcher dispatcher = request.getRequestDispatcher("/employee"); //request.setAttribute(Constants.TITLE, "Home"); dispatcher.forward(request, response); } } else { RequestDispatcher dispatcher = request.getRequestDispatcher("/uploadEmp.jsp"); //request.setAttribute(Constants.TITLE, "Home"); dispatcher.forward(request, response); } }
From source file:control.UploadFile.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try {//www .j a v a2 s . c o m boolean ismultipart = ServletFileUpload.isMultipartContent(request); if (!ismultipart) { } else { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; System.out.println(request); try { items = upload.parseRequest(request); } catch (Exception e) { } Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) { } else { String itemname = item.getName(); if (itemname == null || itemname.equals("")) { continue; } String filename = FilenameUtils.getName(itemname); File f = checkExist(filename); item.write(f); request.getRequestDispatcher("/ideaCreated.jsp").forward(request, response); } } } } catch (Exception e) { } finally { out.close(); } }
From source file:com.dien.upload.server.UploadShpServlet.java
/** * Override executeAction to save the received files in a custom place and delete this items from session. *//*from w ww . j a v a 2 s .c o m*/ @Override public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException { JSONObject obj = new JSONObject(); HttpSession session = request.getSession(); User users = (User) session.getAttribute("user"); if (users != null && users.isDataAuth()) { for (FileItem item : sessionFiles) { if (false == item.isFormField()) { try { // 1. ? File file = File.createTempFile(item.getFieldName(), ".zip"); item.write(file); FileInputStream fis = new FileInputStream(file); if (fis.available() > 0) { System.out.println("File has " + fis.available() + " bytes"); // 2.zip CopyFile copyFile = new CopyFile(); SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); // String tmpFolder = Config.getOutPath() + File.separator + item.getFieldName() + "_" + df.format(new Date()) + "_" + new Random().nextInt(1000); copyFile.delFolder(tmpFolder); copyFile.newFolder(tmpFolder); ZipUtil.unZip(file.getAbsolutePath(), tmpFolder + File.separator, true); // 3.???shp ArrayList<String> slist = new ArrayList<String>(); getAllFile(new File(tmpFolder), slist); if (slist.size() > 0) { ArrayList<String> msglist = new ArrayList<String>(); if (checkShpFileComplete(slist.get(0), msglist)) { // 4. shp // SDEWrapper sde = new SDEWrapper(Config.getProperties()); File shpFile = new File(slist.get(0)); String path = shpFile.getPath(); String layerName = shpFile.getName(); layerName = layerName.substring(0, layerName.indexOf(".")); // ??? // ?? layerName = basis.generatorTableName(layerName); session.setAttribute(layerName, path); // sde.shpToSde(path, layerName); // 5. ? // logger.info("--" + file.getAbsolutePath() + "--isexist: "+ file.exists()); // / Save a list with the received files receivedFiles.put(item.getFieldName(), file); receivedContentTypes.put(item.getFieldName(), item.getContentType()); /// Compose a xml message with the full file information obj.put("fieldname", item.getFieldName()); obj.put("name", item.getName()); obj.put("size", item.getSize()); obj.put("type", item.getContentType()); obj.put("layerName", layerName); obj.put("ret", true); obj.put("msg", "??"); } else { obj.put("ret", false); obj.put("msg", Util.listToWhere(msglist, ",")); } } else { obj.put("ret", false); obj.put("msg", "zipshp"); } } else { obj.put("ret", false); obj.put("msg", "?"); } } catch (IOException e) { obj.put("ret", false); obj.put("msg", "shpshp?????"); } catch (InterruptedException e) { obj.put("ret", false); obj.put("msg", "??"); } catch (Exception e) { obj.put("ret", false); obj.put("msg", "??"); } } } } else { obj.put("msg", "??"); } removeSessionFileItems(request); return obj.toString(); }
From source file:it.marcoberri.mbmeteo.action.UploadFile.java
/** * Handles the HTTP/*from w w w . jav a2 s. c o m*/ * <code>POST</code> method. * * @param request servlet request * @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 { // checks if the request actually contains upload file if (!ServletFileUpload.isMultipartContent(request)) { return; } // configures some settings final DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(THRESHOLD_SIZE); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); final ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(MAX_FILE_SIZE); upload.setSizeMax(REQUEST_SIZE); // constructs the directory path to store upload file final String uploadPath = ConfigurationHelper.prop.getProperty("import.loggerEasyWeather.filepath"); final File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { FileUtils.forceMkdir(uploadDir); } try { // parses the request's content to extract file data final List formItems = upload.parseRequest(request); Iterator iter = formItems.iterator(); // iterates over form's fields while (iter.hasNext()) { final FileItem item = (FileItem) iter.next(); // processes only fields that are not form fields if (item.isFormField()) { continue; } final String fileName = new File(item.getName()).getName(); final String filePath = uploadPath + File.separator + fileName; final File storeFile = new File(filePath); item.write(storeFile); } request.setAttribute("message", "Upload has been done successfully!"); } catch (final Exception ex) { request.setAttribute("message", "There was an error: " + ex.getMessage()); } final ExecuteImport i = new ExecuteImport(); Thread t = new Thread(i); t.start(); }
From source file:net.jforum.core.support.vraptor.DefaultLogicLocator.java
@SuppressWarnings({ "deprecation", "unchecked" }) private void handleMultipartRequest(VRaptorServletRequest servletRequest) { if (!FileUploadBase.isMultipartContent(servletRequest)) { return;// w w w. j av a2 s . c o m } // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(4096 * 16, this.temporaryDirectory); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> fileItems; // assume we know there are two files. The first file is a small // text file, the second is unknown and is written to a file on // the server try { fileItems = upload.parseRequest(servletRequest); } catch (FileUploadException e) { logger.warn("There was some problem parsing this multipart request, or someone is not sending a " + "RFC1867 compatible multipart request.", e); return; } for (FileItem item : fileItems) { if (item.isFormField()) { servletRequest.addParameterValue(item.getFieldName(), item.getString()); } else { if (!item.getName().trim().equals("")) { try { File file = File.createTempFile("vraptor.", ".upload"); item.write(file); UploadedFileInformation fileInformation = new BasicUploadedFileInformation(file, item.getName(), item.getContentType()); this.registeUploadedFile(servletRequest, item.getFieldName(), fileInformation); } catch (Exception e) { logger.error("Nasty uploaded file " + item.getName(), e); } } else { logger.debug("A file field was empy: " + item.getFieldName()); } } } }
From source file:com.hzc.framework.ssh.controller.WebUtil.java
/** * jsonp?//from w ww.ja va2s.c o m * + ? * * @param path * @param ufc * @return * @throws Exception */ public static <T> T uploadMultiAndProgress(String path, Class<T> c, UploadFileNewCall ufc, final ProgressListener pl) throws RuntimeException { try { HttpServletRequest request = getReq(); // final HttpSession session = getSession(); ServletContext servletContext = getServletContext(); File file = new File(servletContext.getRealPath(path)); if (!file.exists()) file.mkdir(); DiskFileItemFactory fac = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(fac); upload.setHeaderEncoding("UTF-8"); upload.setProgressListener(pl); List<FileItem> fileItems = upload.parseRequest(request); T obj = c.newInstance(); Field[] declaredFields = c.getDeclaredFields(); for (FileItem item : fileItems) { if (!item.isFormField()) { String name = item.getName(); String type = item.getContentType(); if (StringUtils.isNotBlank(name)) { File f = new File(file + File.separator + name); item.write(f); ufc.file(obj, f, name, name, item.getSize(), type); // ???? } } else { String name = item.getFieldName(); // ??,?? for (Field field : declaredFields) { field.setAccessible(true); String fieldName = field.getName(); if (name.equals(fieldName)) { String value = item.getString("UTF-8"); if (null == value) { continue; } Class<?> type = field.getType(); if (type == Long.class) { field.set(obj, Long.parseLong(value)); } else if (type == String.class) { field.set(obj, value); } else if (type == Byte.class) { field.set(obj, Byte.parseByte(value)); } else if (type == Integer.class) { field.set(obj, Integer.parseInt(value)); } else if (type == Character.class) { field.set(obj, value.charAt(0)); } else if (type == Boolean.class) { field.set(obj, Boolean.parseBoolean(value)); } else if (type == Double.class) { field.set(obj, Double.parseDouble(value)); } else if (type == Float.class) { field.set(obj, Float.parseFloat(value)); } } } } } return obj; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:gov.nist.appvet.tool.AsynchronousService.java
public boolean saveFileUpload(FileItem fileItem, String outputFilePath) { try {/*from w ww. ja v a2 s . c o m*/ if (fileItem == null) { log.error("fileItem 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; } }