List of usage examples for org.apache.commons.fileupload FileItem write
void write(File file) throws Exception;
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;/*from w w w . ja v a2s. 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:com.intranet.intr.contabilidad.EmpControllerGastos.java
@RequestMapping(value = "EupdateGastoRF.htm", method = RequestMethod.POST) public String EupdateGastoRF_post(@ModelAttribute("ga") gastosR ga, BindingResult result, HttpServletRequest request) {//from w w w .j ava 2 s .c om String mensaje = ""; String ruta = "redirect:EGastos.htm"; //MultipartFile multipart = c.getArchivo(); System.out.println("olaEnviarMAILS"); String ubicacionArchivo = "C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\fotosfacturas"; //File file=new File(ubicacionArchivo,multipart.getOriginalFilename()); //String ubicacionArchivo="C:\\"; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> partes = upload.parseRequest(request); for (FileItem item : partes) { if (gr.getIdgasto() != 0) { if (gastosRService.existe(item.getName()) == false) { System.out.println("updateeeNOMBRE FOTO: " + item.getName()); File file = new File(ubicacionArchivo, item.getName()); item.write(file); gr.setNombreimg(item.getName()); gastosRService.updateGasto(gr); } } else ruta = "redirect:EGastos.htm"; } System.out.println("Archi subido correctamente"); } catch (Exception ex) { System.out.println("Error al subir archivo" + ex.getMessage()); } return ruta; }
From source file:com.eufar.asmm.server.UploadImage.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("UploadImage - the function started"); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(MAX_MEMORY_SIZE); String uploadFolder = getServletContext().getRealPath("") + DATA_DIRECTORY; ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(MAX_REQUEST_SIZE); double maxSize = (MAX_REQUEST_SIZE / 1024) / 1024; System.out.println("UploadImage - max image size: " + maxSize + " Mbytes"); try {//ww w . j av a 2 s . c o m @SuppressWarnings("rawtypes") List items = upload.parseRequest(request); @SuppressWarnings("rawtypes") Iterator iter = items.iterator(); while (iter.hasNext()) { Object obj = iter.next(); org.apache.commons.fileupload.FileItem item = (org.apache.commons.fileupload.FileItem) obj; String fileExt = FilenameUtils.getExtension(item.getName()); if (fileExt.matches("(jpg|jpeg|bmp|png|JPG|JPEG|BMP|PNG)")) { System.out.println("UploadImage - image accepted"); if (!item.isFormField()) { File uploadedFile = File.createTempFile("tmp_", "." + fileExt, new File(uploadFolder)); item.write(uploadedFile); double fileSize = item.getSize(); fileSize = (fileSize / 1024) / 1024; response.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); response.getWriter().write(uploadedFile.getName()); System.out.println("UploadImage - " + uploadedFile.getPath() + ": upload ok..."); System.out.println("UploadImage - " + uploadedFile.getPath() + ": " + fileSize + " MBytes"); if (new File(uploadedFile.getPath()).isFile()) { System.out.println("PrintFunction - picture (webapps): the file exists."); } else { System.out.println("PrintFunction - picture (webapps): the file doesn't exist."); } if (new File(uploadedFile.getPath()).isFile()) { System.out.println("PrintFunction - picture (webapps): the file can be read."); } else { System.out.println("PrintFunction - picture (webapps): the file can't be read."); } } else { System.out.println("UploadImage - a problem occured with the file format"); } } else { System.out.println("UploadImage - image rejected: wrong format"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); response.getWriter().write("format"); } } } catch (Exception ex) { System.out.println("UploadImage - a problem occured: " + ex); response.getWriter().write("ERROR:" + ex.getMessage()); } }
From source file:Ctrl.Upload.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w ww. jav a 2s .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 writer = response.getWriter(); try { if (!ServletFileUpload.isMultipartContent(request)) { // if not, we stop here writer.println("Error: Form must has enctype=multipart/form-data."); writer.flush(); return; } // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(MEMORY_THRESHOLD); // sets temporary location to store files factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); // sets maximum size of upload file upload.setFileSizeMax(MAX_FILE_SIZE); // sets maximum size of request (include file + form data) upload.setSizeMax(MAX_REQUEST_SIZE); // constructs the directory path to store upload file // this path is relative to application's directory String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY; // creates the directory if it does not exist File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } List<FileItem> formItems = upload.parseRequest(request); if (formItems != null && formItems.size() > 0) { // iterates over form's fields for (FileItem item : formItems) { // processes only fields that are not form fields if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); String filePath = uploadPath + File.separator + fileName; File storeFile = new File(filePath); // saves the file on disk item.write(storeFile); request.setAttribute("ten", fileName); request.setAttribute("msg", UPLOAD_DIRECTORY + "/" + fileName); request.setAttribute("message", "Upload has been done successfully >>" + UPLOAD_DIRECTORY + "/" + fileName); } } } } catch (Exception ex) { request.setAttribute("message", "There was an error: " + ex.getMessage()); } // redirects client to message page getServletContext().getRequestDispatcher("/Product.jsp").forward(request, response); }
From source file:database.FileMgr.java
public void upload(HttpServletRequest request) throws Exception { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = upload.parseRequest(request); Iterator iterator = items.iterator(); while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); if (!item.isFormField()) { String fileName = item.getName(); if (!path.exists()) { boolean status = path.mkdirs(); }/*from www .j ava2 s. c o m*/ String dir = path + "/" + fileName; File uploadedFile = new File(dir); if (!(uploadedFile.exists() && !uploadedFile.isDirectory())) { //System.out.println(uploadedFile.getAbsolutePath()); item.write(uploadedFile); } else { throw new Exception("File exist"); } } } } }
From source file:com.intranet.intr.contabilidad.EmpControllerGastos.java
@RequestMapping(value = "EaddGastoRF.htm", method = RequestMethod.POST) public String addGastoRF_post(@ModelAttribute("ga") gastosR ga, BindingResult result, HttpServletRequest request) {//from w w w . j av a 2 s. c o m String mensaje = ""; String ruta = "redirect:EGastos.htm"; gastosR gr = new gastosR(); //MultipartFile multipart = c.getArchivo(); System.out.println("olaEnviarMAILS"); String ubicacionArchivo = "C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\fotosfacturas"; //File file=new File(ubicacionArchivo,multipart.getOriginalFilename()); //String ubicacionArchivo="C:\\"; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> partes = upload.parseRequest(request); for (FileItem item : partes) { if (idPC != 0) { gr.setIdgasto(idPC); if (gastosRService.existe(item.getName()) == false) { System.out.println("NOMBRE FOTO: " + item.getName()); File file = new File(ubicacionArchivo, item.getName()); item.write(file); gr.setNombreimg(item.getName()); gastosRService.insertar(gr); } } else ruta = "redirect:EGastos.htm"; } System.out.println("Archi subido correctamente"); } catch (Exception ex) { System.out.println("Error al subir archivo" + ex.getMessage()); } return ruta; }
From source file:com.dien.manager.servlet.UploadShpServlet.java
/** * Override executeAction to save the received files in a custom place and delete this items from session. *//* w w w . jav a 2 s .c om*/ @Override public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException { String response = ""; int cont = 0; HttpSession session = request.getSession(); User users = (User) session.getAttribute("user"); if (users != null && users.isDataAuth()) { for (FileItem item : sessionFiles) { if (false == item.isFormField()) { cont++; 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(); String tmpFolder = Config.getOutPath() + File.separator + item.getFieldName(); 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 response += "<file-" + cont + "-field>" + item.getFieldName() + "</file-" + cont + "-field>\n"; response += "<file-" + cont + "-name>" + item.getName() + "</file-" + cont + "-name>\n"; response += "<file-" + cont + "-size>" + item.getSize() + "</file-" + cont + "-size>\n"; response += "<file-" + cont + "-type>" + item.getContentType() + "</file-" + cont + "type>\n"; response += "<file-" + cont + "-layerid>" + layerName + "</file-" + cont + "layerid>\n"; } else { response += "<file-" + cont + "-error>" + Util.listToWhere(msglist, ",") + "</file-" + cont + "error>\n"; } } else { response += "<file-" + cont + "-error>zipshp</file-" + cont + "error>\n"; } } else { response += "<file-" + cont + "-error>?</file-" + cont + "error>\n"; } } catch (IOException e) { response += "<file-" + cont + "-error>shpshp??????</file-" + cont + "error>\n"; } catch (InterruptedException e) { response += "<file-" + cont + "-error>??</file-" + cont + "error>\n"; } catch (Exception e) { response += "<file-" + cont + "-error>???</file-" + cont + "error>\n"; } } } } else { response += "<file-" + cont + "-error>???</file-" + cont + "error>\n"; } // / Remove files from session because we have a copy of them removeSessionFileItems(request); // / Send information of the received files to the client. return "<response>\n" + response + "</response>\n"; }
From source file:com.zving.cms.site.Site.java
public static void uploadSite(HttpServletRequest request, HttpServletResponse response) { try {/* w w w. ja v a 2 s . c om*/ DiskFileItemFactory fileFactory = new DiskFileItemFactory(); ServletFileUpload fu = new ServletFileUpload(fileFactory); List fileItems = fu.parseRequest(request); fu.setHeaderEncoding("UTF-8"); Iterator iter = fileItems.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!(item.isFormField())) { String OldFileName = item.getName(); LogUtil.info("Upload Site FileName:" + OldFileName); long size = item.getSize(); if ((((OldFileName == null) || (OldFileName.equals("")))) && (size == 0L)) { continue; } OldFileName = OldFileName.substring(OldFileName.lastIndexOf("\\") + 1); String ext = OldFileName.substring(OldFileName.lastIndexOf(".")); if (!(ext.toLowerCase().equals(".dat"))) { response.sendRedirect("SiteImportStep1.jsp?Error=1"); return; } String FileName = "SiteUpload_" + DateUtil.getCurrentDate("yyyyMMddHHmmss") + ".dat"; String Path = Config.getContextRealPath() + "WEB-INF/data/backup/"; item.write(new File(Path + FileName)); response.sendRedirect("SiteImportStep2.jsp?FileName=" + FileName); } } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.ekitap.controller.AdminUrunController.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// www. ja va2 s .co 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"); response.setCharacterEncoding("ISO-8859-9"); String adminPath = request.getServletPath(); String url = null; String adi = request.getParameter("adi"); ArrayList<KategoriBean> liste = null; ArrayList<YazarBean> yazarListe = null; ArrayList<YayinEviBean> yayinEviListe = null; ArrayList<UrunlerBean> urunListe = null; ArrayList<UrunlerBean> urunGuncelListe = null; ArrayList<UrunResimBean> liste_resim = null; ArrayList liste_fiyat = null; ArrayList<OzellikBean> liste_ozellik; ArrayList<UrunOzellikBean> liste_urun_ozellik; ArrayList<StokBean> liste_stok; int sayfa = 1; int sayfaSayisi = (int) UrunlerDAO.sayfaSayisi(UrunlerDAO.getUrunAdet(), sayfaBasinaUrun); if (adminPath.equals("/urungoster")) { System.out.println(request.getParameter("id")); try { sayfa = Integer.parseInt(request.getParameter("id")); if (sayfa <= 0 || sayfa > sayfaSayisi) { sayfa = 1; } } catch (Exception e) { sayfa = 1; } int baslangicSayisi = (sayfa - 1) * sayfaBasinaUrun; urunListe = UrunlerDAO.getUrunListele(baslangicSayisi, sayfaBasinaUrun); if (urunListe != null) { request.setAttribute("urunliste", urunListe); request.setAttribute("sayfasayisi", sayfaSayisi); } url = "/WEB-INF/view/adminpanel" + adminPath + ".jsp"; request.getRequestDispatcher(url).forward(request, response); } else if (adminPath.equals("/urunekle")) { if (adi == null || adi.trim().isEmpty()) { liste = KategoriDAO.getKategoriListele(); yazarListe = YazarDAO.getYazarListele(); yayinEviListe = YayinEviDAO.getYayinEviListele(); if (liste != null) { request.setAttribute("katliste", liste); } if (yazarListe != null) { request.setAttribute("yazarliste", yazarListe); } if (yayinEviListe != null) { request.setAttribute("yayinliste", yayinEviListe); } url = "/WEB-INF/view/adminpanel" + adminPath + ".jsp"; request.getRequestDispatcher(url).forward(request, response); } // rn ekle else { int urunid; try { // System.out.println(request.getParameter("urunID")); urunid = Integer.parseInt(request.getParameter("urunID")); // System.out.println(urunid); } catch (Exception e) { urunid = 0; } // int yayin = Integer.parseInt(request.getParameter("yayin")); // int yazar = Integer.parseInt(request.getParameter("yazar")); int katidd = Integer.parseInt(request.getParameter("katidd")); UrunlerBean urunler = new UrunlerBean(0, request.getParameter("adi"), 0, 0, katidd, request.getParameter("aciklama")); int urunID = UrunlerDAO.setUrunEkle(urunler, urunid); adminPath = "/urunguncelle"; response.sendRedirect("/urunguncelle?urunID=" + urunID); // url = "/WEB-INF/view/adminpanel" + adminPath + ".jsp"; // request.getRequestDispatcher(url).forward(request, response); } } else if (adminPath.equals("/urunguncelle")) { liste = KategoriDAO.getKategoriListele(); yazarListe = YazarDAO.getYazarListele(); yayinEviListe = YayinEviDAO.getYayinEviListele(); String urunid = request.getParameter("urunID"); liste_resim = UrunlerDAO.getResimListele(Integer.parseInt(urunid)); liste_fiyat = UrunlerDAO.getUrunFiyat(Integer.parseInt(urunid)); liste_ozellik = UrunlerDAO.getOzellik(); liste_urun_ozellik = UrunlerDAO.getUrunOzellik(Integer.parseInt(urunid)); liste_stok = UrunlerDAO.getUrunStok(Integer.parseInt(urunid)); if (urunid == null || urunid.trim().isEmpty()) { return; } urunGuncelListe = UrunlerDAO.getUrunGuncelBilgi(urunid); if (liste != null) { request.setAttribute("katliste", liste); } if (yazarListe != null) { request.setAttribute("yazarliste", yazarListe); } if (yayinEviListe != null) { request.setAttribute("yayinliste", yayinEviListe); } if (urunGuncelListe != null) { request.setAttribute("guncelurun", urunGuncelListe); } if (liste_resim != null) { request.setAttribute("resimliste", liste_resim); } if (liste_fiyat != null) { request.setAttribute("fiyatliste", liste_fiyat); } if (liste_ozellik != null) { request.setAttribute("ozellikliste", liste_ozellik); } if (liste_urun_ozellik != null) { request.setAttribute("urunozellikliste", liste_urun_ozellik); } if (liste_stok != null) { request.setAttribute("stokliste", liste_stok); } url = "/WEB-INF/view/adminpanel" + adminPath + ".jsp"; request.getRequestDispatcher(url).forward(request, response); } else if (adminPath.equals("/yazarekle")) { System.out.println(request.getParameter("yazaradi")); //burdan cek YazarBean yazar = new YazarBean(0, request.getParameter("yazarad"), request.getParameter("yazarsoyad"), request.getParameter("yazarmail")); // System.out.println(request.getParameter("yazarad")+request.getParameter("yazarsoyad")+request.getParameter("yazarmail")); YazarDAO.setYazarEkle(yazar); } else if (adminPath.equals("/yayineviekle")) { YayinEviBean yayinEvi = new YayinEviBean(0, request.getParameter("yayinad"), request.getParameter("yayinadres"), request.getParameter("yayinmail")); YayinEviDAO.setYayinEviEkle(yayinEvi); } else if (adminPath.equals("/resimekle")) { int urunID = Integer.parseInt(request.getParameter("urunID")); System.out.println(urunID); boolean isMultipart = ServletFileUpload.isMultipartContent(request); String name = null; // process only if it is multipart content 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 { // Parse the request List<FileItem> multiparts = upload.parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { name = new File(item.getName()).getName(); item.write(new File(UPLOAD_DIRECTORY + File.separator + name)); } } } catch (Exception e) { e.printStackTrace(); } } liste_resim = UrunlerDAO.resimKaydet(urunID, name); request.setAttribute("resimliste", liste_resim); url = "/WEB-INF/view/adminpanel" + adminPath + ".jsp"; request.getRequestDispatcher(url).forward(request, response); } else if (adminPath.equals("/fiyatekle")) { float vergiOnce = Float.parseFloat(request.getParameter("vergionce")); float vergiSonra = Float.parseFloat(request.getParameter("vergisonra")); int urunID = Integer.parseInt(request.getParameter("urunID")); UrunlerDAO.setUrunFiyat(urunID, vergiOnce, vergiSonra); } else if (adminPath.equals("/ozellikekle")) { String urunid = request.getParameter("urunID"); if (urunid == null || urunid.trim().isEmpty()) { return; } int i = 1; ArrayList<UrunOzellikBean> a = new ArrayList(); UrunOzellikBean urunOzellik; while (request.getParameter("field" + Integer.toString(i)) != null) { urunOzellik = new UrunOzellikBean(Integer.parseInt(urunid), Integer.parseInt(request.getParameter("ofield" + Integer.toString(i))), request.getParameter("field" + Integer.toString(i))); a.add(urunOzellik); i++; } UrunlerDAO.setUrunOzellik(a); // for (UrunOzellikBean object : a) { // System.out.println(object.getDeger()+object.getOzellikID()); // } } else if (adminPath.equals("/stokekle")) { String urunid = request.getParameter("urunID"); if (urunid == null || urunid.trim().isEmpty()) { return; } try { int stok = Integer.parseInt(request.getParameter("stok")); UrunlerDAO.setUrunStok(new StokBean(0, Integer.parseInt(urunid), stok)); } catch (Exception e) { } } }
From source file:controller.categoryServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String catimage = ""; String nameCategory = ""; String command = ""; int catogory_id = 0; String catogory_imagehidden = ""; String catogory_image = ""; if (!ServletFileUpload.isMultipartContent(request)) { // if not, we stop here PrintWriter writer = response.getWriter(); writer.println("Error: Form must has enctype=multipart/form-data."); writer.flush();/*from ww w . jav a2s. c om*/ return; } // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(MEMORY_THRESHOLD); // sets temporary location to store files factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); // sets maximum size of upload file upload.setFileSizeMax(MAX_FILE_SIZE); // sets maximum size of request (include file + form data) upload.setSizeMax(MAX_REQUEST_SIZE); // constructs the directory path to store upload file // this path is relative to application's directory String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY; // creates the directory if it does not exist File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } try { // parses the request's content to extract file data @SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(request); if (formItems != null && formItems.size() > 0) { // iterates over form's fields for (FileItem item : formItems) { // processes only fields that are not form fields if (!item.isFormField()) { catimage = new File(item.getName()).getName(); String filePath = uploadPath + File.separator + catimage; File storeFile = new File(filePath); item.write(storeFile); } else if (item.getFieldName().equals("name")) { nameCategory = item.getString(); } else if (item.getFieldName().equals("command")) { command = item.getString(); } else if (item.getFieldName().equals("catid")) { catogory_id = Integer.parseInt(item.getString()); } else if (item.getFieldName().equals("catogery_imagehidden")) { catogory_imagehidden = item.getString(); } } } } catch (Exception ex) { request.setAttribute("message", "There was an error: " + ex.getMessage()); } String url = "", error = ""; if (nameCategory.equals("")) { error = "Vui lng nhp tn danh mc!"; request.setAttribute("error", error); } HttpSession session = request.getSession(); try { if (error.length() == 0) { CategoryEntity c = new CategoryEntity(nameCategory, catimage); switch (command) { case "insert": if (cate.getListCategoryByName(nameCategory).size() > 0) { System.out.println("ten k "); out.println("ten k dc trung nhau"); out.flush(); return; } else { cate.insertCategory(c); request.setAttribute("er", "thanh cong"); url = "/java/admin/ql-category.jsp"; } break; case "update": if (cate.getListCategoryByName(nameCategory).size() > 0) { System.out.println("ten k "); out.println("ten k dc trung nhau"); out.flush(); return; } else { cate.updateCategory(nameCategory, catimage, catogory_id); url = "/java/admin/ql-category.jsp"; } break; } } else { url = "/java/admin/add-category.jsp"; } } catch (Exception e) { } response.sendRedirect(url); }