List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest
public List parseRequest(HttpServletRequest request) throws FileUploadException
From source file:com.ikon.servlet.admin.ReportServlet.java
@SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("doPost({}, {})", request, response); request.setCharacterEncoding("UTF-8"); String action = ""; String userId = request.getRemoteUser(); updateSessionManager(request);//from w w w. ja v a 2 s.c o m try { if (ServletFileUpload.isMultipartContent(request)) { InputStream is = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); Report rp = new Report(); for (Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem item = it.next(); if (item.isFormField()) { if (item.getFieldName().equals("action")) { action = item.getString("UTF-8"); } else if (item.getFieldName().equals("rp_id")) { rp.setId(Integer.parseInt(item.getString("UTF-8"))); } else if (item.getFieldName().equals("rp_name")) { rp.setName(item.getString("UTF-8")); } else if (item.getFieldName().equals("rp_active")) { rp.setActive(true); } } else { is = item.getInputStream(); rp.setFileName(FilenameUtils.getName(item.getName())); rp.setFileMime(MimeTypeConfig.mimeTypes.getContentType(item.getName())); rp.setFileContent(SecureStore.b64Encode(IOUtils.toByteArray(is))); is.close(); } } if (action.equals("create")) { long id = ReportDAO.create(rp); // Activity log UserActivity.log(userId, "ADMIN_REPORT_CREATE", Long.toString(id), null, rp.toString()); list(userId, request, response); } else if (action.equals("edit")) { Report tmp = ReportDAO.findByPk(rp.getId()); tmp.setActive(rp.isActive()); tmp.setFileContent(rp.getFileContent()); tmp.setFileMime(rp.getFileMime()); tmp.setFileName(rp.getFileName()); tmp.setName(rp.getName()); ReportDAO.update(tmp); // Activity log UserActivity.log(userId, "ADMIN_REPORT_EDIT", Long.toString(rp.getId()), null, rp.toString()); list(userId, request, response); } else if (action.equals("delete")) { ReportDAO.delete(rp.getId()); // Activity log UserActivity.log(userId, "ADMIN_REPORT_DELETE", Long.toString(rp.getId()), null, null); list(userId, request, response); } } } catch (DatabaseException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (FileUploadException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } }
From source file:com.kk.dic.action.Upload.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); out = response.getWriter();//from w ww .j av a2s.c o m Connection con; PreparedStatement pstm = null; String fname = ""; String keyword = ""; String cd = ""; String a = (String) request.getSession().getAttribute("email"); System.out.println("User Name : " + a); try { boolean isMultipartContent = ServletFileUpload.isMultipartContent(request); if (!isMultipartContent) { return; } FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); out.print("one"); try { List<FileItem> fields = upload.parseRequest(request); Iterator<FileItem> it = fields.iterator(); if (!it.hasNext()) { return; } while (it.hasNext()) { FileItem fileItem = it.next(); if (fileItem.getFieldName().equals("name")) { fname = fileItem.getString(); System.out.println("File Name" + fname); } else if (fileItem.getFieldName().equals("keyword")) { keyword = fileItem.getString(); System.out.println("File Keyword" + keyword); } else { } boolean isFormField = fileItem.isFormField(); if (isFormField) { } else { out.print("one"); try { con = Dbconnection.getConnection(); pstm = con.prepareStatement( "insert into files (file, keyword, filetype, filename, CDate, owner, size, data, frank, file_key)values(?,?,?,?,?,?,?,?,?,?)"); out.println("getD " + fileItem.getName()); String str = getStringFromInputStream(fileItem.getInputStream()); // secretkey generating KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); SecretKey secretKey = keyGen.generateKey(); System.out.println("secret key:" + secretKey); //converting secretkey to String byte[] be = secretKey.getEncoded();//encoding secretkey String skey = Base64.encode(be); System.out.println("converted secretkey to string:" + skey); String cipher = new encryption().encrypt(str, secretKey); System.out.println(str); //for get extension from given file String b = fileItem.getName().substring(fileItem.getName().lastIndexOf('.')); System.out.println("File Extension" + b); pstm.setBinaryStream(1, fileItem.getInputStream()); pstm.setString(2, keyword); pstm.setString(3, b); pstm.setString(4, fname); pstm.setDate(5, getCurrentDate()); pstm.setString(6, a); pstm.setLong(7, fileItem.getSize()); pstm.setString(8, cipher); pstm.setString(9, "0"); pstm.setString(10, skey); /*Cloud Start*/ File f = new File("D:/" + fileItem.getName()); out.print("<br/>" + f.getName()); FileWriter fw = new FileWriter(f); fw.write(cipher); fw.close(); Ftpcon ftpcon = new Ftpcon(); ftpcon.upload(f, fname); /*Cloud End*/ int i = pstm.executeUpdate(); if (i == 1) { response.sendRedirect("upload.jsp?msg=success"); } else { response.sendRedirect("upload.jsp?msgg=failed"); } con.close(); } catch (Exception e) { out.println(e); } } } } catch (Exception ex) { out.print(ex); Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex); } } finally { out.close(); } }
From source file:com.chrischurchwell.jukeit.server.ServerHandler.java
@Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Debug.debug("Handling Web Request: ", target); if (target.equalsIgnoreCase("/")) { response.setContentType("text/html;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true);/*from w w w. jav a 2 s .c o m*/ Template template = cfg.getTemplate("index.html"); Map<String, Object> dataRoot = new HashMap<String, Object>(); dataRoot.put("serverName", JukeIt.getInstance().getConfig().getString("serverName")); dataRoot.put("allowUpload", JukeIt.getInstance().getConfig().getBoolean("allowWebServerUploads")); dataRoot.put("files", JukeIt.getServerFileList()); try { template.process(dataRoot, response.getWriter()); } catch (TemplateException e) { // TODO Auto-generated catch block e.printStackTrace(); } return; } if (target.equalsIgnoreCase("/robots.txt")) { response.setContentType("text/plain;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); response.getWriter().println("User-agent: *"); response.getWriter().println("Disallow: /"); return; } if (target.equalsIgnoreCase("/upload")) { if (!JukeIt.getInstance().getConfig().getBoolean("allowWebServerUploads")) { return; } response.setContentType("text/html;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); if (!ServletFileUpload.isMultipartContent(request)) { response.getWriter().println("No File Upload Detected"); return; } /* Straight from commons.io docs */ // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request try { List<FileItem> items = castList(FileItem.class, upload.parseRequest(request)); // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { //processFormField(item); } else { //processUploadedFile(item); //String fieldName = item.getFieldName(); //String fileName = item.getName(); //String contentType = item.getContentType(); //boolean isInMemory = item.isInMemory(); //long sizeInBytes = item.getSize(); if (!item.getName().endsWith(".ogg") && !item.getName().endsWith(".wav") && !item.getName().endsWith(".mp3")) { response.getWriter().println("File must be a .ogg or .wave"); return; } String name = item.getName().replace(" ", "_"); File uploadedFile = new File(JukeIt.getInstance().getDataFolder(), "music/" + name); item.write(uploadedFile); response.getWriter().println("1"); return; } } } catch (FileUploadException e) { response.getWriter().println(e.getMessage()); return; } catch (Exception e) { response.getWriter().println(e.getMessage()); return; } return; } }
From source file:com.esri.gpt.control.filter.MultipartWrapper.java
/** * Construct with a current HTTP servlet request. * @param request the current HTTP servlet request * @throws FileUploadException if an exception occurs during file upload *///www . j av a2 s . c o m public MultipartWrapper(HttpServletRequest request) throws FileUploadException { super(request); getLogger().finer("Handling multipart content."); // initialize parameters _fileParameters = new HashMap<String, FileItem>(); _formParameters = new HashMap<String, String[]>(); int nFileSizeMax = 100000000; int nSizeThreshold = 500000; String sTmpFolder = ""; // make the file item factory DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(nSizeThreshold); if (sTmpFolder.length() > 0) { File fTmpFolder = new File(sTmpFolder); factory.setRepository(fTmpFolder); } // make the file upload object ServletFileUpload fileUpload = new ServletFileUpload(); fileUpload.setFileItemFactory(factory); fileUpload.setFileSizeMax(nFileSizeMax); // parse the parameters associated with the request List items = fileUpload.parseRequest(request); String[] aValues; ArrayList<String> lValues; for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); getLogger().finer("FileItem=" + item); if (item.isFormField()) { String sName = item.getFieldName(); String sValue = item.getString(); if (_formParameters.containsKey(sName)) { aValues = _formParameters.get(sName); lValues = new ArrayList<String>(Arrays.asList(aValues)); lValues.add(sValue); aValues = lValues.toArray(new String[0]); } else { aValues = new String[1]; aValues[0] = sValue; } _formParameters.put(sName, aValues); } else { _fileParameters.put(item.getFieldName(), item); request.setAttribute(item.getFieldName(), item); } } }
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 {/*from w ww . ja va2 s . c o 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:ba.nwt.ministarstvo.server.fileUpload.FileUploadServlet.java
@SuppressWarnings("unchecked") @Override//from w ww.j a v a 2s . c o m protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { ServletRequestContext ctx = new ServletRequestContext(request); if (ServletFileUpload.isMultipartContent(ctx) == false) { sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The servlet can only handle multipart requests." + " This is probably a software bug.")); return; } // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> i = items.iterator(); HashMap<String, String> params = new HashMap<String, String>(); HashMap<String, File> files = new HashMap<String, File>(); while (i.hasNext() == true) { FileItem item = i.next(); if (item.isFormField() == true) { String param = item.getFieldName(); String value = item.getString(); // System.out.println(getClass().getName() + ": param=" // + param + ", value=" + value); params.put(param, value); } else { if (item.getSize() == 0) { continue; // ignore zero-length files } File tempf = File.createTempFile(request.getRemoteAddr() + "-" + item.getFieldName() + "-", ""); item.write(tempf); files.put(item.getFieldName(), tempf); // System.out.println("Creating temporary file " // + tempf.getAbsolutePath()); } } // populate, invoke the listener, delete files if needed, // send response FileUploadAction action = (FileUploadAction) actionClass.newInstance(); BeanUtils.populate(action, params); // populate the object action.setFileList(files); FormResponse resp = action.onSubmit(this, request); if (resp.isDeleteFiles()) { Iterator<Map.Entry<String, File>> j = files.entrySet().iterator(); while (j.hasNext()) { Map.Entry<String, File> entry = j.next(); File f = entry.getValue(); f.delete(); } } sendResponse(response, resp); return; } catch (Exception e) { e.printStackTrace(); sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getClass().getName() + ": " + e.getMessage())); } }
From source file:com.naval.persistencia.hibernate.SubirArchivo.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from w ww. j a va2 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 { String idSolicitud = request.getParameter("idSolicitud"); String accion = request.getParameter("accion"); if (accion != null && "editarSolicitud".equals(accion)) { ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory()); PrintWriter writer = response.getWriter(); List<FileItem> items; try { items = uploadHandler.parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { FileItem actual = null; actual = item; String fileName = actual.getName(); String str = request.getSession().getServletContext().getRealPath("/adjuntos/"); fileName = idSolicitud + "-" + fileName; // nos quedamos solo con el nombre y descartamos el path File fichero = new File(str + "\\" + fileName); try { actual.write(fichero); String aux = "{" + "\"name\":\"" + fichero.getName() + "\",\"size\":\"" + 2000 + "\",\"url\":\"/adjuntos/" + fichero.getName() + "\",\"thumbnailUrl\":\"/thumbnails/" + fichero.getName() + "\",\"deleteUrl\":\"/Subir?file=" + fichero.getName() + "\",\"deleteType\":\"DELETE" + "\",\"type\":\"" + fichero.getName() + "\"}"; writer.write("{\"files\":[" + aux + "]}"); } catch (Exception e) { } } } } catch (Exception ex) { } } else { processRequest(request, response); } }
From source file:com.pagoadalabs.fileupload.controller.FileController.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*ww w .j a va 2 s.c o 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 { // Check that we have a file upload request isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); if (!isMultipart) { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); return; } 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("e://temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // 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()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if (fileName.lastIndexOf("\\") >= 0) { 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("</body>"); out.println("</html>"); } catch (Exception ex) { System.out.println(ex); } }
From source file:gov.nih.nci.queue.servlet.FileUploadServlet.java
/** * ************************************************* * URL: /upload doPost(): upload the files and other parameters * * @param request/*from www . ja va 2s .co m*/ * @param response * @throws javax.servlet.ServletException * @throws java.io.IOException * ************************************************** */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Create an object for JSON response. ResponseModel rm = new ResponseModel(); // Set response type to json response.setContentType("application/json"); PrintWriter writer = response.getWriter(); // Get property values. // SOCcer related. final Double estimatedThreshhold = Double .valueOf(PropertiesUtil.getProperty("gov.nih.nci.soccer.computing.time.threshhold").trim()); // FileUpload Settings. final String repositoryPath = PropertiesUtil.getProperty("gov.nih.nci.queue.repository.dir"); final String strOutputDir = PropertiesUtil.getProperty("gov.nih.cit.soccer.output.dir").trim(); final long fileSizeMax = 10000000000L; // 10G LOGGER.log(Level.INFO, "repository.dir: {0}, filesize.max: {1}, time.threshhold: {2}", new Object[] { repositoryPath, fileSizeMax, estimatedThreshhold }); // Check that we have a file upload request // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); // Ensuring that the request is actually a file upload request. if (isMultipart) { // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); //upload file dirctory. If it does not exist, create one. File f = new File(repositoryPath); if (!f.exists()) { f.mkdir(); } // Set factory constraints // factory.setSizeThreshold(yourMaxMemorySize); // Configure a repository factory.setRepository(new File(repositoryPath)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(fileSizeMax); try { // Parse the request List<FileItem> items = upload.parseRequest(request); // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (!item.isFormField()) { // Handle file field. String fileName = item.getName(); rm.setFileName(fileName); String contentType = item.getContentType(); rm.setFileType(contentType); long sizeInBytes = item.getSize(); rm.setFileSize(String.valueOf(sizeInBytes)); String inputFileId = new UniqueIdUtil(fileName).getInputUniqueID(); rm.setInputFileId(inputFileId); String absoluteInputFileName = repositoryPath + File.separator + inputFileId; rm.setRepositoryPath(repositoryPath); // Write file to the destination folder. File inputFile = new File(absoluteInputFileName); item.write(inputFile); // Validation. InputFileValidator validator = new InputFileValidator(); List<String> validationErrors = validator.validateFile(inputFile); if (validationErrors == null) { // Pass validation // check estimatedProcessingTime. SoccerServiceHelper soccerHelper = new SoccerServiceHelper(strOutputDir); Double estimatedTime = soccerHelper.getEstimatedTime(absoluteInputFileName); rm.setEstimatedTime(String.valueOf(estimatedTime)); if (estimatedTime > estimatedThreshhold) { // STATUS: QUEUE (Ask client for email) // Construct Response String in JSON format. rm.setStatus("queue"); } else { // STATUS: PASS (Ask client to confirm calculate) // all good. Process the output and Go to result page directly. rm.setStatus("pass"); } } else { // STATUS: FAIL // Did not pass validation. // Construct Response String in JSON format. rm.setStatus("invalid"); rm.setDetails(validationErrors); } } else { // TODO: Handle Form Fields such as SOC_SYSTEM. } // End of isFormField } } catch (Exception e) { LOGGER.log(Level.SEVERE, "FileUploadException or FileNotFoundException. Error Message: {0}", new Object[] { e.getMessage() }); rm.setStatus("fail"); rm.setErrorMessage( "Oops! We met with problems when uploading your file. Error Message: " + e.getMessage()); } // Send the response. ObjectMapper jsonMapper = new ObjectMapper(); LOGGER.log(Level.INFO, "Response: {0}", new Object[] { jsonMapper.writeValueAsString(rm) }); // Generate metadata file new MetadataFileUtil(rm.getInputFileId(), repositoryPath) .generateMetadataFile(jsonMapper.writeValueAsString(rm)); // Responde to the client. writer.print(jsonMapper.writeValueAsString(rm)); } else { // The request is NOT actually a file upload request writer.print("You hit the wrong file upload page. The request is NOT actually a file upload request."); } }
From source file:com.estampate.corteI.servlet.servlets.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* w w w . j a v a2 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"); PrintWriter out = response.getWriter(); dirUploadFiles = getServletContext().getRealPath(getServletContext().getInitParameter("dirUploadFiles")); HttpSession sesion = request.getSession(true); 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 tipo = item.getContentType(); long tamanio = item.getSize(); String extension = nombre.substring(nombre.lastIndexOf(".")); sesion.setAttribute("sArNombre", String.valueOf(nombre)); sesion.setAttribute("sArTipo", String.valueOf(tipo)); sesion.setAttribute("sArExtension", String.valueOf(extension)); File archivo = new File(dirUploadFiles, "nombreRequest" + extension); item.write(archivo); if (archivo.exists()) { response.sendRedirect("uploadsave.jsp"); } else { sesion.setAttribute("sArError", "Ocurrio un error al subir el archiv o"); response.sendRedirect("uploaderror.jsp"); } } } } } catch (FileUploadException e) { sesion.setAttribute("sArError", String.valueOf(e.getMessage())); response.sendRedirect("uploaderror.jsp"); } catch (Exception e) { sesion.setAttribute("sArError", String.valueOf(e.getMessage())); response.sendRedirect("uploaderror.jsp"); } } out.close(); }