List of usage examples for org.apache.commons.fileupload FileItem write
void write(File file) throws Exception;
From source file:com.primeleaf.krystal.web.action.console.CheckInDocumentAction.java
@SuppressWarnings({ "unchecked", "rawtypes" }) public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL); try {//from w ww. ja v a2s. c om if ("POST".equalsIgnoreCase(request.getMethod())) { String errorMessage; String tempFilePath = System.getProperty("java.io.tmpdir"); if (!(tempFilePath.endsWith("/") || tempFilePath.endsWith("\\"))) { tempFilePath += System.getProperty("file.separator"); } tempFilePath += loggedInUser.getUserName() + "_" + session.getId(); String revisionId = "", comments = "", fileName = "", ext = "", version = ""; int documentId = 0; // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); List items = upload.parseRequest((HttpServletRequest) request); upload.setHeaderEncoding(HTTPConstants.CHARACTER_ENCODING); //Create a file upload progress listener Iterator iter = items.iterator(); FileItem item = null; File file = null; while (iter.hasNext()) { item = (FileItem) iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(HTTPConstants.CHARACTER_ENCODING); if (name.equals("documentid")) { try { documentId = Integer.parseInt(value); } catch (Exception ex) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input"); return (new CheckInDocumentView(request, response)); } } else if (name.equals("revisionid")) { revisionId = value; } else if (name.equals("txtNote")) { comments = value; } else if ("version".equalsIgnoreCase(name)) { version = value; } } else { fileName = item.getName(); ext = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase(); file = new File(tempFilePath + "." + ext); item.write(file); } } iter = null; Document document = DocumentDAO.getInstance().readDocumentById(documentId); if (document == null) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid document"); return (new CheckInDocumentView(request, response)); } if (document.getStatus().equalsIgnoreCase(Hit.STATUS_AVAILABLE)) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid check-in"); return (new CheckInDocumentView(request, response)); } revisionId = document.getRevisionId(); DocumentClass documentClass = DocumentClassDAO.getInstance() .readDocumentClassById(document.getClassId()); AccessControlManager aclManager = new AccessControlManager(); ACL acl = aclManager.getACL(documentClass, loggedInUser); if (!acl.canCheckin()) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Access Denied"); return (new CheckInDocumentView(request, response)); } if (file.length() <= 0) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Zero length document"); return (new CheckInDocumentView(request, response)); } if (file.length() > documentClass.getMaximumFileSize()) { //code for checking maximum size of document in a class request.setAttribute(HTTPConstants.REQUEST_ERROR, "Document size exceeded"); return (new CheckInDocumentView(request, response)); } String indexValue = ""; String indexName = ""; Hashtable indexRecord = new Hashtable(); for (IndexDefinition indexDefinition : documentClass.getIndexDefinitions()) { indexName = indexDefinition.getIndexColumnName(); Iterator itemsIterator = items.iterator(); while (itemsIterator.hasNext()) { FileItem fileItem = (FileItem) itemsIterator.next(); if (fileItem.isFormField()) { String name = fileItem.getFieldName(); String value = fileItem.getString(HTTPConstants.CHARACTER_ENCODING); if (name.equals(indexName)) { indexValue = value; if (indexValue != null) { if (indexDefinition.isMandatory()) { if (indexValue.trim().length() <= 0) { errorMessage = "Invalid input for " + indexDefinition.getIndexDisplayName(); request.setAttribute(HTTPConstants.REQUEST_ERROR, errorMessage); return (new CheckInDocumentView(request, response)); } } if (IndexDefinition.INDEXTYPE_NUMBER .equalsIgnoreCase(indexDefinition.getIndexType())) { if (indexValue.trim().length() > 0) { if (!GenericValidator.matchRegexp(indexValue, HTTPConstants.NUMERIC_REGEXP)) { errorMessage = "Invalid input for " + indexDefinition.getIndexDisplayName(); request.setAttribute(HTTPConstants.REQUEST_ERROR, errorMessage); return (new CheckInDocumentView(request, response)); } } } else if (IndexDefinition.INDEXTYPE_DATE .equalsIgnoreCase(indexDefinition.getIndexType())) { if (indexValue.trim().length() > 0) { if (!GenericValidator.isDate(indexValue, "yyyy-MM-dd", true)) { errorMessage = "Invalid input for " + indexDefinition.getIndexDisplayName(); request.setAttribute(HTTPConstants.REQUEST_ERROR, errorMessage); return (new CheckInDocumentView(request, response)); } } } if (indexValue.trim().length() > indexDefinition.getIndexMaxLength()) { //code for checking maximum length of index field errorMessage = "Document index length exceeded. Index Name :" + indexDefinition.getIndexDisplayName() + " [ " + "Index Length : " + indexDefinition.getIndexMaxLength() + " , " + "Actual Length : " + indexValue.length() + " ]"; request.setAttribute(HTTPConstants.REQUEST_ERROR, errorMessage); return (new CheckInDocumentView(request, response)); } } indexRecord.put(indexName, indexValue); } } fileItem = null; } // while iter itemsIterator = null; } // while indexDefinitionItr CheckedOutDocument checkedOutDocument = new CheckedOutDocument(); checkedOutDocument.setDocumentId(documentId); // Added by Viral Visaria. For the Version Control minor and major. // In minor revision increment by 0.1. (No Changes required for the minor revision its handled in the core logic) // In major revision increment by 1.0 (Below chages are incremented by 0.9 and rest 0.1 will be added in the core logic. (0.9 + 0.1 = 1.0) double rev = Double.parseDouble(revisionId); if ("major".equals(version)) { rev = Math.floor(rev); rev = rev + 0.9; revisionId = String.valueOf(rev); } checkedOutDocument.setRevisionId(revisionId); checkedOutDocument.setUserName(loggedInUser.getUserName()); RevisionManager revisionManager = new RevisionManager(); revisionManager.checkIn(checkedOutDocument, documentClass, indexRecord, file, comments, ext, loggedInUser.getUserName()); //revision id incremented by 0.1 for making entry in audit log rev += 0.1; revisionId = String.valueOf(rev); //add to audit log AuditLogManager.log(new AuditLogRecord(documentId, AuditLogRecord.OBJECT_DOCUMENT, AuditLogRecord.ACTION_CHECKIN, loggedInUser.getUserName(), request.getRemoteAddr(), AuditLogRecord.LEVEL_INFO, "Document ID : " + documentId + " Revision ID :" + revisionId, "Checked In")); request.setAttribute(HTTPConstants.REQUEST_MESSAGE, "Document checked in successfully"); return (new CheckInDocumentView(request, response)); } int documentId = 0; try { documentId = Integer.parseInt( request.getParameter("documentid") != null ? request.getParameter("documentid") : "0"); } catch (Exception e) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input"); return (new CheckInDocumentView(request, response)); } Document document = DocumentDAO.getInstance().readDocumentById(documentId); if (document == null) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid document"); return (new CheckInDocumentView(request, response)); } if (!Hit.STATUS_LOCKED.equalsIgnoreCase(document.getStatus())) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid checkin"); return (new CheckInDocumentView(request, response)); } DocumentClass documentClass = DocumentClassDAO.getInstance() .readDocumentClassById(document.getClassId()); LinkedHashMap<String, String> documentIndexes = IndexRecordManager.getInstance() .readIndexRecord(documentClass, documentId, document.getRevisionId()); request.setAttribute("DOCUMENTCLASS", documentClass); request.setAttribute("DOCUMENT", document); request.setAttribute("DOCUMENTINDEXES", documentIndexes); } catch (Exception e) { e.printStackTrace(); } return (new CheckInDocumentView(request, response)); }
From source file:com.food.adminservlet.FoodServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int foodid = 0; String foodName = ""; String fooddesc = ""; Double foodprice = 0.0;/*from ww w . j a va 2 s . c o m*/ String foodCategory = ""; PrintWriter out = response.getWriter(); isMultipart = ServletFileUpload.isMultipartContent(request); FoodBean bkfood = new FoodBean(); FoodBL foodbl = new FoodBL(); try { response.setContentType("text/html"); //java.io.PrintWriter out = response.getWriter( ); 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("c:\\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(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()) { if (fi.getFieldName().equals("foodid")) { foodid = Integer.parseInt(fi.getString()); } if (fi.getFieldName().equals("foodname")) { foodName = fi.getString(); } if (fi.getFieldName().equals("fooddesc")) { fooddesc = fi.getString(); } if (fi.getFieldName().equals("foodprice")) { foodprice = Double.parseDouble(fi.getString()); } if (fi.getFieldName().equals("foodcate")) { foodCategory = fi.getString(); } out.println("<br>"); } 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>"); } } out.println(fileName); bkfood.setFoodId(foodid); bkfood.setFoodName(foodName); bkfood.setFoodPrice(foodprice); bkfood.setFoodCateg(foodCategory); bkfood.setFoodDesc(fooddesc); bkfood.setFoodRetreiveImage(fileName); // bkfood.setFoodimage(request.getPart("foodimage")); bkfood.setFoodstatus("Y"); int chk = foodbl.addFoodItems(bkfood); out.println(chk); if (chk == 1) { response.sendRedirect("food.jsp"); } } catch (Exception ex) { out.println(ex); } }
From source file:Controller.ControllerCustomers.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from www . j av a 2 s. c om * @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 { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { } else { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { items = upload.parseRequest(request); } catch (Exception e) { e.printStackTrace(); } Iterator iter = items.iterator(); Hashtable params = new Hashtable(); String fileName = null; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { params.put(item.getFieldName(), item.getString()); } else { try { String itemName = item.getName(); fileName = itemName.substring(itemName.lastIndexOf("\\") + 1); String RealPath = getServletContext().getRealPath("/") + "upload\\" + fileName; String username = (String) params.get("txtusername"); String password = (String) params.get("txtpassword"); String hoten = (String) params.get("txthoten"); String gioitinh = (String) params.get("txtgioitinh"); String email = (String) params.get("txtemail"); String role = (String) params.get("txtrole"); String anh = (String) params.get("txtanh"); //Update product if (fileName.equals("")) { Customer Cus = new Customer(username, password, hoten, gioitinh, email, role, anh); CustomerDAO.SuaThongTinKhachHang(Cus); RequestDispatcher rd = request.getRequestDispatcher("CustomerDao.jsp"); rd.forward(request, response); } else { // bat dau ghi file File savedFile = new File(RealPath); item.write(savedFile); //ket thuc ghi Customer Cus = new Customer(username, password, hoten, gioitinh, email, role, "upload\\" + fileName); CustomerDAO.SuaThongTinKhachHang(Cus); RequestDispatcher rd = request.getRequestDispatcher("CustomerDao.jsp"); rd.forward(request, response); } } catch (Exception e) { System.out.println(e); RequestDispatcher rd = request.getRequestDispatcher("InformationError.jsp"); rd.forward(request, response); } } } } }
From source file:com.square.composant.envoi.email.square.server.servlet.UploadFichierServlet.java
/** {@inheritDoc} */ @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final boolean isMultipart = ServletFileUpload.isMultipartContent(request); // Cration d'un DiskFileItemFactory pour stocker les fichiers. if (isMultipart) { try {/*w ww. ja va 2 s. co m*/ final FileItemFactory factory = new DiskFileItemFactory(); final ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding(ComposantEnvoiEmailConstants.ENCODAGE_UTF_8); // Rcupration des items contenus dans la requte final List<FileItem> listeItems = upload.parseRequest(request); // Parcours des items for (FileItem item : listeItems) { // Fichier uploader if (!item.isFormField()) { // Nom du fichier String nomFichier = ""; // on verifie si il y a un backslash if (item.getName().indexOf("\\") != -1) { // [\\\\] = expression rgulire pour dcouper suivant le backslash final String[] tabNomFichier = item.getName().split("\\\\"); nomFichier = tabNomFichier[tabNomFichier.length - 1]; } else { nomFichier = item.getName(); } // Type MIME final String typeMime = item.getContentType(); // Cration d'un fichier temporaire String prefixe = nomFichier; String suffixe = null; if (nomFichier.indexOf(".") != -1) { final int indexPoint = nomFichier.lastIndexOf("."); prefixe = nomFichier.substring(0, indexPoint); suffixe = nomFichier.substring(indexPoint); } if (prefixe.length() < 3) { response.getOutputStream() .print(ComposantEnvoiEmailConstants.ERREUR_UPLOAD_FICHIER_NOM_INCORRECT); } else { final File fichierTemporaire = File.createTempFile(prefixe, suffixe); item.write(fichierTemporaire); // Renvoi des infos concernant le fichier final StringBuffer infosFichier = new StringBuffer(); infosFichier.append(ComposantEnvoiEmailConstants.PARAM_NOM_FICHIER) .append(ComposantEnvoiEmailConstants.EGAL).append(nomFichier); infosFichier.append(ComposantEnvoiEmailConstants.ET); infosFichier.append(ComposantEnvoiEmailConstants.PARAM_PATH_FICHIER_TEMP) .append(ComposantEnvoiEmailConstants.EGAL) .append(fichierTemporaire.getCanonicalPath()); infosFichier.append(ComposantEnvoiEmailConstants.ET); infosFichier.append(ComposantEnvoiEmailConstants.PARAM_TYPE_MIME) .append(ComposantEnvoiEmailConstants.EGAL).append(typeMime); response.getOutputStream().print(URLEncoder.encode(infosFichier.toString(), ComposantEnvoiEmailConstants.ENCODAGE_UTF_8)); } } } } catch (FileUploadException e) { response.getOutputStream().print(ComposantEnvoiEmailConstants.ERREUR_UPLOAD_FICHIER); } catch (Exception e) { response.getOutputStream().print(ComposantEnvoiEmailConstants.ERREUR_UPLOAD_FICHIER); } } }
From source file:com.esd.cs.worker.WorkerController.java
/** * ?// w ww. j a v a 2 s . c o m * * @param request * @param response * @return */ public Map<String, String> importfile(String upLoadPath, HttpServletRequest request, HttpServletResponse response) { // ??? // String fileType = "xls"; DiskFileItemFactory factory = new DiskFileItemFactory(); // factory.setSizeThreshold(5 * 1024); // factory.setRepository(new File(upLoadPath)); ServletFileUpload fileUpload = new ServletFileUpload(factory); Map<String, String> result = new HashMap<String, String>(); if (LoadUpFileMaxSize != null && !StringUtils.equals(LoadUpFileMaxSize.trim(), "")) { // ? fileUpload.setSizeMax(Integer.valueOf(LoadUpFileMaxSize) * 1024 * 1024); } try { // ? List<FileItem> items = fileUpload.parseRequest(request); for (FileItem item : items) { // ? if (!item.isFormField()) { // ?? String fileName = item.getName(); // ?? String fileEnd = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); // ?? String uuid = UUID.randomUUID().toString(); // StringBuffer sbRealPath = new StringBuffer(); sbRealPath.append(upLoadPath).append(uuid).append(".").append(fileEnd); // File file = new File(sbRealPath.toString()); item.write(file); logger.info("?,filePath" + file.getPath()); // result.put("filePath", file.getPath()); // form?? } else { // item.getFieldName():??keyitem.getString()??value result.put(item.getFieldName(), item.getString()); } } } catch (Exception e) { // ??? result.put("fileError", ",??" + LoadUpFileMaxSize + "M!"); logger.error("uplaodWorkerFileError:{}", e.getMessage()); return result; } return result; }
From source file:Atualizar.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(req); String caminho;/*from ww w . j av a 2s. co m*/ if (isMultipart) { try { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = (List<FileItem>) upload.parseRequest(req); for (FileItem item : items) { if (item.isFormField()) { resp.getWriter() .println("No campo file" + this.getServletContext().getRealPath("/img")); resp.getWriter().println("Name campo: " + item.getFieldName()); resp.getWriter().println("Value campo: " + item.getString()); req.setAttribute(item.getFieldName(), item.getString()); } else { //caso seja um campo do tipo file resp.getWriter().println("Campo file"); resp.getWriter().println("Name:" + item.getFieldName()); resp.getWriter().println("nome arquivo :" + item.getName()); resp.getWriter().println("Size:" + item.getSize()); resp.getWriter().println("ContentType:" + item.getContentType()); resp.getWriter().println( "C:\\uploads" + File.separator + new Date().getTime() + "_" + item.getName()); if (item.getName() == "" || item.getName() == null) { caminho = this.getServletContext().getRealPath("\\img\\user.jpg"); } else { caminho = "img" + File.separator + new Date().getTime() + "_" + item.getName(); } resp.getWriter().println("Caminho: " + caminho); req.setAttribute("caminho", caminho); File uploadedFile = new File( "E:\\Documentos\\NetBeansProjects\\SisLivros\\web\\" + caminho); item.write(uploadedFile); req.setAttribute("caminho", caminho); // req.getRequestDispatcher("cadastrouser").forward(req, resp); } } } catch (Exception e) { resp.getWriter().println("ocorreu um problema ao fazer o upload: " + e.getMessage()); } } }
From source file:it.biblio.servlets.Inserimento_Ristampa.java
/** * metodo per gestire l'upload di file//from www .jav a 2 s . c om * * @param request * @param response * @param k * @return * @throws IOException */ private boolean upload(HttpServletRequest request) throws IOException, Exception { Map<String, Object> ristampe = new HashMap<String, Object>(); int idopera = Integer.parseInt(request.getParameter("id")); if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory fif = new DiskFileItemFactory(); ServletFileUpload sfo = new ServletFileUpload(fif); List<FileItem> items = sfo.parseRequest(request); for (FileItem item : items) { String fname = item.getFieldName(); if (item.isFormField() && fname.equals("ISBN") && !item.getString().isEmpty()) { ristampe.put("isbn", item.getString()); } else if (item.isFormField() && fname.equals("numero_pagine") && !item.getString().isEmpty()) { ristampe.put("numpagine", Integer.parseInt(item.getString())); } else if (item.isFormField() && fname.equals("anno_pub") && !item.getString().isEmpty()) { ristampe.put("datapub", item.getString()); } else if (item.isFormField() && fname.equals("editore") && !item.getString().isEmpty()) { ristampe.put("editore", item.getString()); } else if (item.isFormField() && fname.equals("lingua") && !item.getString().isEmpty()) { ristampe.put("lingua", item.getString()); } else if (item.isFormField() && fname.equals("indice") && !item.getString().isEmpty()) { ristampe.put("indice", item.getString()); //se stato inserito un pdf salvo il file e inserisco nella mappa i dati } else if (!item.isFormField() && fname.equals("PDF")) { String name = item.getName(); long size = item.getSize(); if (size > 0 && !name.isEmpty()) { File target = new File(getServletContext().getRealPath("") + File.separatorChar + "PDF" + File.separatorChar + name); item.write(target); ristampe.put("download", "PDF" + File.separatorChar + name); } //salvo l'immagine e inserisco i dati nella mappa } else if (!item.isFormField() && fname.equals("copertina")) { String name = item.getName(); long size = item.getSize(); if (size > 0 && !name.isEmpty()) { File target = new File(getServletContext().getRealPath("") + File.separatorChar + "Copertine" + File.separatorChar + name); item.write(target); ristampe.put("copertina", "Copertine" + File.separatorChar + name); } } } ristampe.put("pubblicazioni", idopera); return Database.insertRecord("ristampe", ristampe); } return false; }
From source file:com.cmart.PageControllers.SellItemImagesController.java
public void saveImages(String baseURL) { //System.out.println("sellitemimagecont: looking for image to upload!"); //System.out.println("saving images :" + baseURL); baseURL = baseURL + "/" + GV.REMOTE_IMAGE_DIR + "/"; // Special case for the thumbnail /*if(this.images.size()>1){ FileItem image = this.images.get(0); /*from w w w. j ava 2 s. c om*/ //TODO: compress an image String[] ext = image.getName().split("\\."); int extIndex = ext.length>0 ? ext.length-1 : 0; String filename = this.itemID + "_" + 0 + "." + ext[extIndex]; String URL = filename; // Setup the thumbnail file File file = new File(GlobalVars.localImageDir, filename); file.setReadable(true, false); file.setWritable(true, false); try { image.write(file); GlobalVars.db.insertThumbnail(this.itemID, URL); } catch (Exception e) { // TODO Auto-generated catch block this.errors.add(new Error("SellItemImagesController (saveImages): Could not save thumbnail", e)); e.printStackTrace(); } }*/ boolean thumbnail = true; // Loop through all the images for (int i = 0; i < this.images.size(); i++) { FileItem image = this.images.get(i); //TODO: make number start from one and only count real images if (image.getSize() > 0) { // Make the file name and path String[] ext = image.getName().split("\\."); int extIndex = ext.length > 0 ? ext.length - 1 : 0; String filename = this.itemID + "_" + (i + 1) + "." + ext[extIndex]; //String URL = filename; // Setup the image file //System.out.println("setting temp dir as the image"); File file = new File(GV.LOCAL_TEMP_DIR, filename + "tmp"); file.setReadable(true, false); file.setWritable(true, false); //System.out.println("URL :" + URL); //System.out.println("name :" + filename); //System.out.println("local :" + GV.LOCAL_IMAGE_DIR); //System.out.println("remote :" + GV.REMOTE_IMAGE_DIR); try { //System.out.println("doing db insert"); GV.DB.insertImage(this.itemID, i + 1, filename, ""); //System.out.println("saving image"); image.write(file); //System.out.println("mkaing file in img dir"); File file2 = new File(GV.LOCAL_IMAGE_DIR, filename); //System.out.println("doing the image resize"); BufferedImage originalImage2 = ImageIO.read(file); int type2 = originalImage2.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage2.getType(); //System.out.println("doing the image resize second step"); BufferedImage resizeImageHintJpg2 = resizeImageWithHint(originalImage2, type2, 500, 450); ImageIO.write(resizeImageHintJpg2, "jpg", file2); try { file.delete(); } catch (Exception e) { } //System.out.println("sellitemimagecont: inserted an image!"); if (thumbnail) { //TODO: some image compression String thumbName = this.itemID + "_" + 0 + "." + ext[extIndex]; GV.DB.insertThumbnail(this.itemID, thumbName); //System.out.println("doing thumbnail"); File thumbFile = new File(GV.LOCAL_IMAGE_DIR, thumbName); // Get a JPEG writer // TODO: other formats?? /*ImageWriter writer = null; Iterator iter = ImageIO.getImageWritersByFormatName("jpg"); if (iter.hasNext()) { writer = (ImageWriter)iter.next(); } // Set the output file ImageOutputStream ios = ImageIO.createImageOutputStream(thumbFile); writer.setOutput(ios); // Set the compression level JPEGImageWriteParam imgparams = new JPEGImageWriteParam(Locale.getDefault()); imgparams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT) ; imgparams.setCompressionQuality(128); // Write the compressed file RenderedImage rendFile = ImageIO.read(file); writer.write(null, new IIOImage(rendFile, null, null), imgparams); // copy file InputStream fin = new FileInputStream(file); OutputStream fout = new FileOutputStream(thumbFile); byte[] buff = new byte[1024]; int len; while((len = fin.read(buff)) > 0) fout.write(buff, 0, len); fin.close(); fout.close(); */ BufferedImage originalImage = ImageIO.read(file2); int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType(); BufferedImage resizeImageHintJpg = resizeImageWithHint(originalImage, type, 100, 100); ImageIO.write(resizeImageHintJpg, "jpg", thumbFile); thumbnail = false; } } catch (Exception e) { // TODO Auto-generated catch block this.errors.add(new Error("SellItemImagesController (saveImages): Could not save image", e)); e.printStackTrace(); } } } if (this.errors.size() == 0 && !this.useHTML5()) { createRedirectURL(); } // Try to save the uploaded files /*try { while(images.hasNext()) { FileItem item = (FileItem) images.next(); System.out.println("doing item 1"); /* * Handle Form Fields. * if(item.isFormField()) { System.out.println("File Name = "+item.getFieldName()+", Value = "+item.getString()); } else { //Handle Uploaded files. System.out.println("Field Name = "+item.getFieldName()+ ", File Name = "+item.getName()+ ", Content type = "+item.getContentType()+ ", File Size = "+item.getSize()); /* * Write file to the ultimate location. * File file = new File(GlobalVars.imageDir,item.getName()); item.write(file); } //System.out.close(); } }catch(Exception ex) { System.out.println("Error encountered while uploading file"); }*/ }
From source file:com.insurance.manage.UploadFile.java
private void uploadLicense(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // boolean isMultipart = ServletFileUpload.isMultipartContent(request); // Create a factory for disk-based file items String custId = null;// w w w.ja v a 2 s. c o m String year = null; String license = null; CustomerManager cManage = new CustomerManager(); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1 * 1024 * 1024); //1 MB factory.setRepository(new File("temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); HttpSession session = request.getSession(); // System.out.println("eCust : "+session.getAttribute("eCust")); // if (session.getAttribute("eCust")!=null) { // Customer cEntity = (Customer)request.getAttribute("eCust"); // System.out.println("CustId : "+cEntity.getName()); // } // Parse the request // System.out.println("--------- Uploading --------------"); try { List /* FileItem */ items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); File fi = null; File file = null; Calendar calendar = Calendar.getInstance(); DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); String fileName = df.format(calendar.getTime()) + ".jpg"; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { // System.out.println(item.getFieldName()+" : "+item.getName()+" : "+item.getString()+" : "+item.getContentType()); if (item.getFieldName().equals("custId") && !item.getString().equals("")) { custId = item.getString(); // System.out.println("custId : "+custId); } if (item.getFieldName().equals("year") && !item.getString().equals("")) { year = item.getString(); // System.out.println("year : "+year); } if (item.getFieldName().equals("license") && !item.getString().equals("")) { license = (String) session.getAttribute(item.getString()); // System.out.println("license : "+license+" : "+session.getAttribute(item.getString())); } } else { // Handle Uploaded files. // System.out.println("Handle Uploaded files."); if (item.getFieldName().equals("vat") && !item.getName().equals("")) { fi = new File(item.getName()); File uploadedFile = new File( getServletContext().getRealPath("/images/license/vat/" + year + fileName)); item.write(uploadedFile); cManage.updatePicture(custId, year, license, "vatpic", year + fileName); } if (item.getFieldName().equals("car") && !item.getName().equals("")) { fi = new File(item.getName()); File uploadedFile = new File( getServletContext().getRealPath("/images/license/car/" + year + fileName)); item.write(uploadedFile); cManage.updatePicture(custId, year, license, "carpic", year + fileName); } if (item.getFieldName().equals("act") && !item.getName().equals("")) { fi = new File(item.getName()); File uploadedFile = new File( getServletContext().getRealPath("/images/license/act/" + year + fileName)); item.write(uploadedFile); cManage.updatePicture(custId, year, license, "actpic", year + fileName); } if (item.getFieldName().equals("chk") && !item.getName().equals("")) { fi = new File(item.getName()); File uploadedFile = new File( getServletContext().getRealPath("/images/license/chk/" + year + fileName)); item.write(uploadedFile); cManage.updatePicture(custId, year, license, "chkpic", year + fileName); } } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } request.setAttribute("url", "setup/CustomerMultiMT.jsp?action=search&custId=" + custId); request.setAttribute("msg", "!!!Uploading !!!"); getServletConfig().getServletContext().getRequestDispatcher("/Reload.jsp").forward(request, response); }
From source file:by.creepid.jsf.fileupload.UploadRenderer.java
/** * Decode any new state of this UIComponent from the request contained in * the specified FacesContext, and store this state as needed. * * During decoding, events may be enqueued for later processing (by event * listeners who have registered an interest), by calling queueEvent(). * * @param context/*from w w w . ja va 2s . c om*/ */ @Override public void decode(FacesContext context) { ExternalContext external = context.getExternalContext(); HttpServletRequest request = (HttpServletRequest) external.getRequest(); String clientId = getClientId(context); FileItem item = (FileItem) request.getAttribute(clientId); ValueExpression valueExpr = getValueExpression("value"); if (valueExpr != null) { UIComponent component = getCurrentComponent(context); if (item.getSize() > 0) { String target = getAttributes().get("target").toString(); String realPath = getServletRealPath(external, target); String fileName = item.getName(); String longFileName = getLongFileName(realPath, fileName); String shortFileName = target + "/" + fileName; //if the target location ends with the forward slash, //just join the target and the filename if (target.endsWith("/")) { shortFileName = target + fileName; } ((EditableValueHolder) component) .setSubmittedValue(new UploadedFile(item, longFileName, shortFileName)); } else { ((EditableValueHolder) component).setSubmittedValue(new UploadedFile()); } ((EditableValueHolder) component).setValid(true); } Object target = getAttributes().get("target"); if (target != null) { String realPath = getServletRealPath(external, target.toString()); File file = new File(getLongFileName(realPath, item.getName())); File parent = file.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } try { if (item.getSize() > 0 && item.getName().length() > 0) { item.write(file); } } catch (Exception ex) { throw new FacesException(ex); } } }