List of usage examples for org.apache.commons.fileupload FileItem write
void write(File file) throws Exception;
From source file:it.unisa.tirocinio.servlet.UploadInformationFilesServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*w w w. j a va 2 s. 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, JSONException { try { response.setContentType("text/html;charset=UTF-8"); response.setHeader("Access-Control-Allow-Origin", "*"); out = response.getWriter(); isMultipart = ServletFileUpload.isMultipartContent(request); StudentDBOperation getSerialNumberObj = new StudentDBOperation(); ConcreteStudent aStudent = null; String serialNumber = null; DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List fileItems = upload.parseRequest(request); Iterator i = fileItems.iterator(); File fileToStore = null; String studentSubfolderPath = filePath; while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); if (fieldName.equals("cvfile")) { fileToStore = new File(studentSubfolderPath + fileSeparator + "CV.pdf"); } else if (fieldName.equals("examsfile")) { fileToStore = new File(studentSubfolderPath + fileSeparator + "ES.pdf"); } fi.write(fileToStore); // out.println("Uploaded Filename: " + fieldName + "<br>"); } else { //out.println("It's not formfield"); //out.println(fi.getString()); aStudent = getSerialNumberObj.getSerialNumberbyFK_Account(Integer.parseInt(fi.getString())); serialNumber = reverseSerialNumber(aStudent.getPrimaryKey()); studentSubfolderPath += fileSeparator + serialNumber; new File(studentSubfolderPath).mkdir(); } } message.put("status", 1); out.print(message.toString()); } catch (IOException ex) { message.put("status", 0); message.put("errorMessage", ex); out.print(message.toString()); Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { message.put("status", 0); message.put("errorMessage", ex); out.print(message.toString()); Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { message.put("status", 0); message.put("errorMessage", ex); out.print(message.toString()); Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (FileUploadException ex) { message.put("status", 0); message.put("errorMessage", ex); out.print(message.toString()); Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { message.put("status", 0); message.put("errorMessage", ex); out.print(message.toString()); Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex); } finally { out.close(); } }
From source file:co.estampas.servlets.guardarEstampa.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from w w w . ja v a 2s .co m * @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 { String rutaImg = "NN"; /* SUBIR LA IMAGEN AL SERVIDOR */ dirUploadFiles = getServletContext().getRealPath(getServletContext().getInitParameter("dirUploadFiles")); if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(new Long(getServletContext().getInitParameter("maxFileSize")).longValue()); List listUploadFiles = null; FileItem item = null; try { listUploadFiles = upload.parseRequest(request); Iterator it = listUploadFiles.iterator(); while (it.hasNext()) { item = (FileItem) it.next(); if (!item.isFormField()) { if (item.getSize() > 0) { String nombre = item.getName(); String extension = nombre.substring(nombre.lastIndexOf(".")); File archivo = new File(dirUploadFiles, nombre); item.write(archivo); if (archivo.exists()) { subioImagen = true; rutaImg = "estampas/" + nombre; // response.sendRedirect("uploadsave.jsp"); } else { subioImagen = false; } } } else { campos.add(item.getString()); } } } catch (FileUploadException e) { subioImagen = false; } catch (Exception e) { subioImagen = false; } } if (subioImagen) { String nombreImg = campos.get(1); processRequest(request, response); EstampaCamiseta estampa = new EstampaCamiseta(); //BUSCO EL ARTISTA QUE VA A GUARDAR LA ESTAMPA this.idArtistax = Integer.parseInt(campos.get(0)); Artista ar = artistaFacade.find(Integer.parseInt(campos.get(0))); estampa.setIdArtista(ar); //TRAIGO EL TAMAO QUE ELIGIERON DE LA ESTAMPA TamanoEstampa tamEstampa = tamanoEstampaFacade.find(Integer.parseInt(campos.get(4))); estampa.setIdTamanoEstampa(tamEstampa); //TRAIGO EL TEMA QUE ELIGIERON DE LA ESTAMPA TemaEstampa temaEstampa = temaEstampaFacade.find(Integer.parseInt(campos.get(2))); estampa.setIdTemaEstampa(temaEstampa); //ASIGNO EL NOMBRE DE LA ESTAMPA estampa.setDescripcion(nombreImg); //ASIGNO LA RUTA DE LA IMAGEN QUE CREO estampa.setImagenes(rutaImg); //ASIGNO LA UBICACION DE LA IMAGEN EN LA CAMISA estampa.setUbicacion(campos.get(5)); //ASIGNO EL PRECIO DE LA IMAGEN QUE CREO estampa.setPrecio(campos.get(3)); //ASIGNO EL ID DEL LUGAR estampa.setIdLugarEstampa(Integer.parseInt(campos.get(5))); //GUARDAR LA ESTAMPA estampaCamisetaFacade.create(estampa); } else { System.out.println("Error al subir imagen"); } campos = new ArrayList<>(); processRequest(request, response); }
From source file:edu.lternet.pasta.portal.UploadEvaluateServlet.java
/** * Process the uploaded file/*from www . java2 s. c o m*/ * * @param item The multipart form file data. * * @return The uploaded file as File object. * * @throws Exception */ private File processUploadedFile(FileItem item) throws Exception { File eml = null; // Process a file upload if (!item.isFormField()) { // Get object information String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); String tmpdir = System.getProperty("java.io.tmpdir"); logger.debug("FILE: " + tmpdir + "/" + fileName); eml = new File(tmpdir + "/" + fileName); item.write(eml); } return eml; }
From source file:ManageViewerFiles.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w ww.j a v a 2s . 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"); PrintWriter out = response.getWriter(); try { //get the viewer files //add more files //delete some files /* TODO output your page here. You may use following sample code. */ String command = request.getParameter("command"); String viewerid = request.getParameter("viewerid"); //System.out.println("Hello World"); //System.out.println(command); //System.out.println(studyid); if (command.equalsIgnoreCase("getViewerFiles")) { //getting viewer files //first get the filenames in the directory. //I will get the list of files in this directory and send it String studyPath = getServletContext().getRealPath("/viewer/" + viewerid); File root = new File(studyPath); File[] list = root.listFiles(); ArrayList<String> fileItemList = new ArrayList<String>(); if (list == null) { System.out.println("List is null"); return; } for (File f : list) { if (f.isDirectory()) { ArrayList<String> dirItems = getFileItems(f.getAbsolutePath(), f.getName()); for (int i = 0; i < dirItems.size(); i++) { fileItemList.add(dirItems.get(i)); } } else { //System.out.println(f.getName()); fileItemList.add(f.getName()); } } System.out.println("**** Printing the fileItems now **** "); String outputStr = ""; for (int i = 0; i < fileItemList.size(); i++) { outputStr += fileItemList.get(i) + "::::"; } out.println(outputStr); } else if (command.equalsIgnoreCase("addViewerFiles")) { //add the files //get the files and add them String studyFolderPath = getServletContext().getRealPath("/viewer/" + viewerid); File studyFolder = new File(studyFolderPath); //process only if its multipart content if (ServletFileUpload.isMultipartContent(request)) { try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()) .parseRequest(request); int cnt = 0; for (FileItem item : multiparts) { if (!item.isFormField()) { // cnt++; String name = new File(item.getName()).getName(); //write the file to disk if (!studyFolder.exists()) { studyFolder.mkdir(); System.out.println("The Folder has been created"); } item.write(new File(studyFolder + File.separator + name)); System.out.println("File name is :: " + name); } } out.print("Files successfully uploaded"); } catch (Exception ex) { //System.out.println("File Upload Failed due to " + ex); out.print("File Upload Failed due to " + ex); } } else { // System.out.println("The request did not include files"); out.println("The request did not include files"); } } else if (command.equalsIgnoreCase("deleteViewerFiles")) { //get the array of files and delete thems String[] mpk; //get the array of file-names mpk = request.getParameterValues("fileNames"); for (int i = 0; i < mpk.length; i++) { String filePath = getServletContext().getRealPath("/viewer/" + viewerid + "/" + mpk[i]); File f = new File(filePath); f.delete(); } } //out.println("</html>"); } catch (Exception ex) { ex.printStackTrace(); } finally { out.close(); } }
From source file:it.geosolutions.geofence.gui.server.UploadServlet.java
@SuppressWarnings("unchecked") @Override//from ww w . j ava 2 s .c om protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // process only multipart requests if (ServletFileUpload.isMultipartContent(req)) { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); File uploadedFile = null; // Parse the request try { List<FileItem> items = upload.parseRequest(req); for (FileItem item : items) { // process only file upload - discard other form item types if (item.isFormField()) { continue; } String fileName = item.getName(); // get only the file name not whole path if (fileName != null) { fileName = FilenameUtils.getName(fileName); } uploadedFile = File.createTempFile(fileName, ""); // if (uploadedFile.createNewFile()) { item.write(uploadedFile); resp.setStatus(HttpServletResponse.SC_CREATED); resp.flushBuffer(); // uploadedFile.delete(); // } else // throw new IOException( // "The file already exists in repository."); } } catch (Exception e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred while creating the file : " + e.getMessage()); } try { String wkt = calculateWKT(uploadedFile); resp.getWriter().print(wkt); } catch (Exception exc) { resp.getWriter().print("Error : " + exc.getMessage()); logger.error("ERROR ********** " + exc); } uploadedFile.delete(); } else { resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "Request contents type is not supported by the servlet."); } }
From source file:com.ckfinder.connector.handlers.command.FileUploadCommand.java
/** * saves temporary file in the correct file path. * * @param path path to save file//from ww w .j a va 2 s .co m * @param item file upload item * @return result of saving, true if saved correctly * @throws Exception when error occurs. */ private boolean saveTemporaryFile(final String path, final FileItem item) throws Exception { File file = new File(path, this.newFileName); AfterFileUploadEventArgs args = new AfterFileUploadEventArgs(); args.setCurrentFolder(this.currentFolder); args.setFile(file); args.setFileContent(item.get()); if (!ImageUtils.isImage(file)) { item.write(file); if (configuration.getEvents() != null) { configuration.getEvents().run(EventTypes.AfterFileUpload, args, configuration); } return true; } else if (ImageUtils.checkImageSize(item.getInputStream(), this.configuration)) { ImageUtils.createTmpThumb(item.getInputStream(), file, getFileItemName(item), this.configuration); if (configuration.getEvents() != null) { configuration.getEvents().run(EventTypes.AfterFileUpload, args, configuration); } return true; } else if (configuration.checkSizeAfterScaling()) { ImageUtils.createTmpThumb(item.getInputStream(), file, getFileItemName(item), this.configuration); if (FileUtils.checkFileSize(configuration.getTypes().get(this.type), file.length())) { if (configuration.getEvents() != null) { configuration.getEvents().run(EventTypes.AfterFileUpload, args, configuration); } return true; } else { file.delete(); this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG; return false; } } //should be unreacheable return false; }
From source file:hd.controller.AddImageToProductServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w . j a v a2 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 { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { //to do } else { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { items = upload.parseRequest(request); } catch (FileUploadException 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("UTF-8")); } else if (!item.isFormField()) { try { long time = System.currentTimeMillis(); String itemName = item.getName(); fileName = time + itemName.substring(itemName.lastIndexOf("\\") + 1); String RealPath = getServletContext().getRealPath("/") + "images\\" + fileName; File savedFile = new File(RealPath); item.write(savedFile); } catch (Exception e) { e.printStackTrace(); } } } String productID = (String) params.get("txtProductId"); System.out.println(productID); String tilte = (String) params.get("newGalleryName"); String description = (String) params.get("GalleryDescription"); String url = "images/" + fileName; ProductDAO productDao = new ProductDAO(); ProductPhoto productPhoto = productDao.insertProductPhoto(tilte, description, url, productID); response.sendRedirect("MyProductDetailServlet?action=showDetail&txtProductID=" + productID); } } catch (Exception e) { e.printStackTrace(); } finally { out.close(); } }
From source file:com.openhr.UploadFile.java
@Override public ActionForward execute(ActionMapping map, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // checks if the request actually contains upload file if (!ServletFileUpload.isMultipartContent(request)) { PrintWriter writer = response.getWriter(); writer.println("Request does not contain upload data"); writer.flush();//w ww . ja va2s. c o m return map.findForward("masteradmin"); } // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(THRESHOLD_SIZE); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(MAX_REQUEST_SIZE); // constructs the directory path to store upload file String uploadPath = 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 List formItems = upload.parseRequest(request); Iterator iter = formItems.iterator(); // iterates over form's fields while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // 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); // Read the file object contents and parse it and store it in the repos FileInputStream fstream = new FileInputStream(storeFile); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; Company comp = null; Branch branch = null; Calendar currDtCal = Calendar.getInstance(); // Zero out the hour, minute, second, and millisecond currDtCal.set(Calendar.HOUR_OF_DAY, 0); currDtCal.set(Calendar.MINUTE, 0); currDtCal.set(Calendar.SECOND, 0); currDtCal.set(Calendar.MILLISECOND, 0); Date now = currDtCal.getTime(); //Read File Line By Line while ((strLine = br.readLine()) != null) { System.out.print("Processing line - " + strLine); String[] lineColumns = strLine.split(COMMA); if (lineColumns.length < 16) { br.close(); in.close(); fstream.close(); throw new Exception("The required columns are missing in the line - " + strLine); } // Format is - // CompID,BranchName,EmpID,EmpFullName,EmpNationalID,BankName,BankBranch,RoutingNo,AccountNo,NetPay,Currency, // residenttype,TaxAmount,EmployerSS,EmployeeSS if (comp == null || comp.getId() != Integer.parseInt(lineColumns[0])) { List<Company> comps = CompanyFactory.findById(Integer.parseInt(lineColumns[0])); if (comps != null && comps.size() > 0) { comp = comps.get(0); } else { br.close(); in.close(); fstream.close(); throw new Exception("Unable to get the details of the company"); } // Check for licenses List<Licenses> compLicenses = LicenseFactory.findByCompanyId(comp.getId()); for (Licenses lis : compLicenses) { if (lis.getActive() == 1) { Date endDate = lis.getTodate(); if (!isLicenseActive(now, endDate)) { br.close(); in.close(); fstream.close(); // License has expired and throw an error throw new Exception("License has expired"); //TODO remove the below code and enable above /*List<Branch> branches = BranchFactory.findByCompanyId(comp.getId()); String branchName = lineColumns[1]; if(branches != null && !branches.isEmpty()) { for(Branch bb: branches) { if(branchName.equalsIgnoreCase(bb.getName())) { branch = bb; break; } } if(branch == null) { Branch bb = new Branch(); bb.setName(branchName); bb.setAddress("NA"); bb.setCompanyId(comp); BranchFactory.insert(bb); List<Branch> lbranches = BranchFactory.findByName(branchName); branch = lbranches.get(0); } }*/ //TODO } else { // License enddate is valid, so lets check the key. String compName = comp.getName(); String licenseKeyStr = LicenseValidator.formStringToEncrypt(compName, endDate); if (LicenseValidator.encryptAndCompare(licenseKeyStr, lis.getLicensekey())) { // License key is valid, so proceed. List<Branch> branches = BranchFactory.findByCompanyId(comp.getId()); String branchName = lineColumns[1]; if (branches != null && !branches.isEmpty()) { for (Branch bb : branches) { if (branchName.equalsIgnoreCase(bb.getName())) { branch = bb; break; } } if (branch == null) { Branch bb = new Branch(); bb.setName(branchName); bb.setAddress("NA"); bb.setCompanyId(comp); BranchFactory.insert(bb); List<Branch> lbranches = BranchFactory.findByName(branchName); branch = lbranches.get(0); } } break; } else { br.close(); in.close(); fstream.close(); throw new Exception("License is tampered. Contact Support."); } } } } } // CompID,BranchName,EmpID,EmpFullName,EmpNationalID,DeptName,BankName,BankBranch,RoutingNo,AccountNo,NetPay,currency,TaxAmt,emprSS,empess,basesalary CompanyPayroll compPayroll = new CompanyPayroll(); compPayroll.setBranchId(branch); compPayroll.setEmployeeId(lineColumns[2]); compPayroll.setEmpFullName(lineColumns[3]); compPayroll.setEmpNationalID(lineColumns[4]); compPayroll.setDeptName(lineColumns[5]); compPayroll.setBankName(lineColumns[6]); compPayroll.setBankBranch(lineColumns[7]); compPayroll.setRoutingNo(lineColumns[8]); compPayroll.setAccountNo(lineColumns[9]); compPayroll.setNetPay(Double.parseDouble(lineColumns[10])); compPayroll.setCurrencySym(lineColumns[11]); compPayroll.setResidentType(lineColumns[12]); compPayroll.setTaxAmount(Double.parseDouble(lineColumns[13])); compPayroll.setEmprSocialSec(Double.parseDouble(lineColumns[14])); compPayroll.setEmpeSocialSec(Double.parseDouble(lineColumns[15])); compPayroll.setBaseSalary(Double.parseDouble(lineColumns[16])); compPayroll.setProcessedDate(now); CompanyPayrollFactory.insert(compPayroll); } //Close the input stream br.close(); in.close(); fstream.close(); } } System.out.println("Upload has been done successfully!"); } catch (Exception ex) { System.out.println("There was an error: " + ex.getMessage()); ex.printStackTrace(); } return map.findForward("MasterHome"); }
From source file:com.liteoc.bean.rule.FileUploadHelper.java
private File processUploadedFile(FileItem item, String dirToSaveUploadedFileIn) { dirToSaveUploadedFileIn = dirToSaveUploadedFileIn == null ? System.getProperty("java.io.tmpdir") : dirToSaveUploadedFileIn;//from ww w.j a v a 2 s. co m String fileName = item.getName(); // Some browsers IE 6,7 getName returns the whole path int startIndex = fileName.lastIndexOf('\\'); if (startIndex != -1) { fileName = fileName.substring(startIndex + 1, fileName.length()); } File uploadedFile = new File(dirToSaveUploadedFileIn + File.separator + fileName); if (fileRenamePolicy != null) { uploadedFile = fileRenamePolicy.rename(uploadedFile); } try { item.write(uploadedFile); } catch (Exception e) { throw new OpenClinicaSystemException(e.getMessage()); } return uploadedFile; }
From source file:forseti.JUploadFichero.java
@SuppressWarnings("rawtypes") public boolean procesaFicheros(HttpServletRequest req, PrintWriter out) { try {//ww w .j a v a 2 s . c o m // construimos el objeto que es capaz de parsear la pericin DiskFileUpload fu = new DiskFileUpload(); // maximo numero de bytes fu.setSizeMax(1024 * 512); // 512 K depura("Ponemos el tamao mximo"); // tamao por encima del cual los ficheros son escritos directamente en disco fu.setSizeThreshold(4096); // directorio en el que se escribirn los ficheros con tamao superior al soportado en memoria fu.setRepositoryPath("/tmp"); // ordenamos procesar los ficheros List fileItems = fu.parseRequest(req); if (fileItems == null) { depura("La lista es nula"); return false; } // Iteramos por cada fichero Iterator i = fileItems.iterator(); FileItem actual = null; depura("estamos en la iteracin"); while ((actual = (FileItem) i.next()) != null) { String fileName = actual.getName(); out.println("<br>Nos han subido el archivo: " + fileName); // construimos un objeto file para recuperar el trayecto completo File fichero = new File(fileName); depura("El nombre del fichero es " + fichero.getName()); // nos quedamos solo con el nombre y descartamos el path fichero = new File("../tomcat/webapps/ROOT/forsetidoc/IMG/" + fichero.getName()); // escribimos el fichero colgando del nuevo path actual.write(fichero); } } catch (Exception e) { if (e != null) depura("Error de Aplicacin " + e.getMessage()); return false; } return true; }