List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory setRepository
public void setRepository(File repository)
From source file:Servlet.UploadServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from w w w .j av a 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 { HttpSession tempSession = request.getSession(); java.lang.System.out.println(tempSession.getAttribute("accountType") + "---------------upload\n"); if (tempSession.getAttribute("accountType") == null || !tempSession.getAttribute("accountType").equals("2")) { response.sendRedirect("login.jsp"); } else { System.out.println("------------------IN UPLOADING PROCESS------------------"); String uploader_id = "", title = "", description = "", importancy = "", category = "", fileName = "", date = ""; File file; int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; String filePath = "G:\\GoogleDrive\\Class file\\Current\\Me\\Web\\Lab\\Project\\Web Project\\ENotice\\src\\main\\webapp\\files\\"; String contentType = request.getContentType(); if ((contentType.indexOf("multipart/form-data") >= 0)) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(maxMemSize); factory.setRepository(new File("C:\\temp\\")); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxFileSize); try { List fileItems = upload.parseRequest(request); Iterator i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { String fieldName = fi.getFieldName(); fileName = fi.getName(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); file = new File(filePath + fileName); fi.write(file); } else if (fi.getFieldName().equals("title")) { title = fi.getString(); } else if (fi.getFieldName().equals("description")) { description = fi.getString(); } else if (fi.getFieldName().equals("importancy")) { importancy = fi.getString(); } else { category = fi.getString(); } } } catch (Exception ex) { System.out.println(ex); } } else { } //transfering data to Upload notice try { String uploaderId = (String) tempSession.getAttribute("id"); System.out.println("id : " + uploaderId); System.out.println(title + " " + description + " " + importancy + " " + category + " " + fileName + " " + uploaderId); Upload upload = new Upload(); upload.upload(uploaderId, title, description, importancy, category, fileName); } catch (Exception e) { System.out.println("Exception in doPost of UploadServlet()"); e.printStackTrace(); } if (request.getAttribute("fromEdit") == null) { //back to upload.jsp System.out.println("fromEdit is null!!!"); System.out.println("position of Notice : " + request.getParameter("positionOfNotice")); response.sendRedirect("upload.jsp"); } else { System.out.println("fromEdit is not null!!!"); RequestDispatcher rd = request.getRequestDispatcher("UploaderNextPrevCombo"); rd.forward(request, response); } } }
From source file:servlets.File_servlets.java
private void add_new_file_handler(HttpServletRequest request, HttpServletResponse response) throws IOException { try {/* w ww.j av a 2s . co m*/ DAO daoInstance; File uploadedFile; Experiment experiment; String parent_dir; String file_name; try { if (!ServletFileUpload.isMultipartContent(request)) { throw new Exception("Erroneus request."); } /** * ******************************************************* * STEP 1 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP. IF * ERROR --> throws exception if not valid session, GO TO STEP * 5b ELSE --> GO TO STEP 2 * ******************************************************* */ Map<String, Cookie> cookies = this.getCookies(request); String loggedUser, loggedUserID = null, sessionToken; if (cookies != null) { loggedUser = cookies.get("loggedUser").getValue(); sessionToken = cookies.get("sessionToken").getValue(); loggedUserID = cookies.get("loggedUserID").getValue(); } else { String apicode = request.getParameter("apicode"); apicode = new String(Base64.decodeBase64(apicode)); loggedUser = apicode.split(":")[0]; sessionToken = apicode.split(":")[1]; } if (!checkAccessPermissions(loggedUser, sessionToken)) { throw new AccessControlException("Your session is invalid. User or session token not allowed."); } if (loggedUserID == null) { daoInstance = DAOProvider.getDAOByName("User"); loggedUserID = ((User) daoInstance.findByID(loggedUser, new Object[] { null, false, true })) .getUserID(); } /** * ******************************************************* * STEP 2 Get the Experiment Object from DB. IF ERROR --> throws * MySQL exception, GO TO STEP 3b ELSE --> GO TO STEP 3 * ******************************************************* */ String experiment_id; if (request.getParameter("experiment_id") != null) { experiment_id = request.getParameter("experiment_id"); } else { experiment_id = cookies.get("currentExperimentID").getValue(); } parent_dir = ""; if (request.getParameter("parent_dir") != null) { parent_dir = request.getParameter("parent_dir"); } file_name = ""; if (request.getParameter("file_name") != null) { file_name = request.getParameter("file_name"); } /** * ******************************************************* * STEP 3 Check that the user is a valid owner for the * experiment. * ******************************************************* */ daoInstance = DAOProvider.getDAOByName("Experiment"); experiment = (Experiment) daoInstance.findByID(experiment_id, null); if (!experiment.isOwner(loggedUserID) && !experiment.isMember(loggedUserID) && !isValidAdminUser(loggedUser)) { throw new AccessControlException( "Cannot add files to selected study. Current user is not a valid member for study " + experiment_id + "."); } /** * ******************************************************* * STEP 4 Read the uploaded file and store in a temporal dir. * ******************************************************* */ FileItem tmpUploadedFile = null; final String CACHE_PATH = "/tmp/"; final int CACHE_SIZE = 500 * (int) Math.pow(10, 6); final int MAX_REQUEST_SIZE = 600 * (int) Math.pow(10, 6); final int MAX_FILE_SIZE = 500 * (int) Math.pow(10, 6); //TODO: READ FROM SETTINGS // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setRepository(new File(CACHE_PATH)); factory.setSizeThreshold(CACHE_SIZE); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(MAX_REQUEST_SIZE); upload.setFileSizeMax(MAX_FILE_SIZE); // Parse the request List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { if (!item.getName().equals("")) { tmpUploadedFile = item; } } } if (tmpUploadedFile == null) { throw new Exception("The file was not uploaded correctly."); } /** * ******************************************************* * STEP 5 SAVE THE FILE IN THE SERVER. * ******************************************************* */ //First check if the file already exists -> error, probably a previous treatmente exists with the same treatment_id Path tmpDir = Files.createTempDirectory(null); file_name = (file_name.isEmpty() ? tmpUploadedFile.getName() : file_name); uploadedFile = new File(tmpDir.toString(), file_name); try { tmpUploadedFile.write(uploadedFile); if (request.getParameter("credentials") != null) { byte[] decoded = Base64.decodeBase64(request.getParameter("credentials")); String[] credentials = new String(decoded).split(":", 2); experiment.setDataDirectoryUser(credentials[0]); experiment.setDataDirectoryPass(credentials[1]); } else if (request.getParameter("apikey") != null) { experiment.setDataDirectoryApiKey(request.getParameter("apikey")); } FileManager.getFileManager(DATA_LOCATION).saveFiles(new File[] { uploadedFile }, experiment.getDataDirectoryInformation(), parent_dir); } catch (IOException e) { // Directory creation failed throw new Exception( "Unable to save the uploded file. Please check if the Tomcat user has read/write permissions over the data application directory."); } finally { tmpUploadedFile.delete(); uploadedFile.delete(); Files.delete(tmpDir); } } catch (Exception e) { ServerErrorManager.handleException(e, File_servlets.class.getName(), "add_new_file_handler", e.getMessage()); } finally { /** * ******************************************************* * STEP 5b CATCH ERROR, CLEAN CHANGES. throws SQLException * ******************************************************* */ if (ServerErrorManager.errorStatus()) { response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); } else { JsonObject obj = new JsonObject(); obj.add("success", new JsonPrimitive(true)); response.getWriter().print(obj.toString()); } } } catch (Exception e) { ServerErrorManager.handleException(e, File_servlets.class.getName(), "add_new_file_handler", e.getMessage()); response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); } }
From source file:servlets.generar.java
protected String[] subirExamen(HttpServletRequest request) throws FileUploadException, Exception { String datos[] = new String[2]; String imgDir = config.getServletContext().getRealPath("/examenes/") + "/"; File dir = new File(imgDir); dir.mkdirs();//from w ww.ja v a 2 s . c o m DiskFileItemFactory fabrica = new DiskFileItemFactory(); fabrica.setSizeThreshold(1024); fabrica.setRepository(dir); ServletFileUpload upload = new ServletFileUpload(fabrica); List<FileItem> partes = upload.parseRequest(request); for (FileItem item : partes) { if (item.isFormField()) { datos[0] = item.getString(); System.out.println(item.getString()); } else { System.out.println("Subiendo"); File archivo = new File(imgDir, item.getName()); item.write(archivo); datos[1] = item.getName(); } } return datos; }
From source file:servlets.Handler.java
/** * /*from w w w.java2s . c o m*/ * @param request * @return */ private Response send_email(HttpServletRequest request) { UserDTO user = (UserDTO) request.getSession().getAttribute("user"); if (user != null) { int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; ServletContext context = request.getServletContext(); String contentType = request.getContentType(); if ((contentType.indexOf("multipart/form-data") >= 0)) { String email = ""; String subject = ""; try { 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")); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxFileSize); List fileItems = upload.parseRequest(request); FileItem fi = (FileItem) fileItems.get(0); ; subject = request.getParameter("subject"); email = java.net.URLDecoder.decode(request.getParameter("email"), "UTF-8"); //ARREGLAR ESTOOOOOOOOOOOOOOOOO return this.facade.sendEmail(user, subject, email, fi); } catch (FileUploadException ex) { ex.printStackTrace(); return ResponseHelper.getResponse(-3, "No se pudo subir el archivo", null); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); System.out.println("email:" + email); return ResponseHelper.getResponse(-3, "No se pudo parsear el email", null); } catch (Exception ex) { ex.printStackTrace(); return ResponseHelper.getResponse(-3, "No se pudo escribir el archivo en el disco", null); } } else { return ResponseHelper.getResponse(-2, "Cabecera HTTP erronea", null); } } return ResponseHelper.getResponse(-2, "Login is required", null); }
From source file:servlets.NewFile.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* w w w . j a v a2 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, IOException { int maxFileSize = 1000 * 1024; int maxMemSize = 1000 * 1024; // String contentType = request.getContentType(); // if ((contentType.contains("multipart/form-data"))) { // DiskFileItemFactory factory = new DiskFileItemFactory(); // } String contentType = request.getContentType(); response.setContentType("multipart/form-data"); if ((contentType.contains("multipart/form-data"))) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(maxMemSize); factory.setRepository(new File(".")); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxFileSize); String path = getServletContext().getRealPath("") + File.separator + "files"; File uploadDir = new File(path); if (!uploadDir.exists()) { uploadDir.mkdir(); } try { List<FileItem> formItems = upload.parseRequest(request); if (formItems != null && formItems.size() > 0) { for (FileItem item : formItems) { if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); String filePath = path + File.separator + fileName; File storeFile = new File(filePath); request.getSession(true).setAttribute("filePath", filePath); // guardamos el fichero en el disco item.write(storeFile); } } } } catch (FileUploadException ex) { Logger.getLogger(NewCarta.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(NewCarta.class.getName()).log(Level.SEVERE, null, ex); } request.getRequestDispatcher("/crearCarta.jsp").forward(request, response); } }
From source file:servlets.Samples_servlets.java
private void send_biocondition_template_document_handler(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {//from w w w.j a v a 2 s .com ArrayList<String> BLOCKED_IDs = new ArrayList<String>(); boolean ROLLBACK_NEEDED = false; DAO dao_instance = null; try { if (!ServletFileUpload.isMultipartContent(request)) { throw new Exception("Erroneus request."); } String user_id = ""; String sessionToken = ""; File xls_file = null; /** * ******************************************************* * STEP 1 Get the request params: read the params and the XLS * file. IF ERROR --> throws SQL Exception, GO TO STEP ? ELSE * --> GO TO STEP 9 * ******************************************************* */ response.reset(); response.addHeader("Access-Control-Allow-Origin", "*"); response.setContentType("text/html"); //Get the data as a JSON format string final String CACHE_PATH = "/tmp/"; final int CACHE_SIZE = 100 * (int) Math.pow(10, 6); final int MAX_REQUEST_SIZE = 20 * (int) Math.pow(10, 6); final int MAX_FILE_SIZE = 20 * (int) Math.pow(10, 6); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setRepository(new File(CACHE_PATH)); factory.setSizeThreshold(CACHE_SIZE); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(MAX_REQUEST_SIZE); upload.setFileSizeMax(MAX_FILE_SIZE); // Parse the request List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { if (!item.getName().equals("")) { //First check if the file already exists -> error, probably a previous treatmente exists with the same treatment_id xls_file = new File(CACHE_PATH + "tmp.xls"); item.write(xls_file); } } else { String name = item.getFieldName(); String value = item.getString(); if ("loggedUser".equals(name)) { user_id = value; } else if ("sessionToken".equals(name)) { sessionToken = value; } } } /** * ******************************************************* * STEP 2 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP AND * IF FILE IS CORRECTLY UPDATED. IF ERROR --> throws exception * if not valid session, GO TO STEP 6b ELSE --> GO TO STEP 3 * ******************************************************* */ if (!checkAccessPermissions(user_id, sessionToken)) { throw new AccessControlException("Your session is invalid. User or session token not allowed."); } if (xls_file == null) { throw new Exception("XLS file was not uploaded correctly."); } /** * ******************************************************* * STEP 2 Parse the XLS file and get the information. IF ERROR * --> throws Exception, GO TO STEP ? ELSE --> GO TO STEP 3 * ******************************************************* */ Object[] parsingResult = BioCondition_XLS_parser.parseXLSfile(xls_file, user_id); ArrayList<BioCondition> biocondition_list = (ArrayList<BioCondition>) parsingResult[0]; HashMap<String, Batch> batchesTable = (HashMap<String, Batch>) parsingResult[1]; HashMap<String, Protocol> protocolsTable = (HashMap<String, Protocol>) parsingResult[2]; /** * ******************************************************* * STEP 3 IF FILE WAS PARSED CORRECTLY ADD THE INFORMATION TO * DATABASE. IF ERROR --> throws SQLException, GO TO STEP ? ELSE * --> GO TO STEP 4 * ******************************************************* */ dao_instance = DAOProvider.getDAOByName("Batch"); dao_instance.disableAutocommit(); ROLLBACK_NEEDED = true; //IF WE ARE HERE IT MEANS THAT APARENTLY EVERTHING WAS OK //therefore WE SHOULD START ADDING THE INFORMATION INTO THE DB for (Batch batch : batchesTable.values()) { String batch_id = dao_instance.getNextObjectID(null); BLOCKED_IDs.add(batch_id); batch.setBatchID(batch_id); //THE BATCH ID SHOULD BE UPDATED IN ALL THE BIOREPLICATES (BECAUSE IS THE SAME OBJECT) dao_instance.insert(batch); } dao_instance = DAOProvider.getDAOByName("Protocol"); //IF WE ARE HERE IT MEANS THAT APARENTLY EVERTHING WAS OK //therefore WE SHOULD START ADDING THE INFORMATION INTO THE DB for (Protocol protocol : protocolsTable.values()) { String protocolID = dao_instance.getNextObjectID(null); BLOCKED_IDs.add(protocolID); protocol.setProtocolID(protocolID); //THE BATCH ID SHOULD BE UPDATED IN ALL THE BIOREPLICATES (BECAUSE IS THE SAME OBJECT) dao_instance.insert(protocol); } dao_instance = DAOProvider.getDAOByName("BioCondition"); for (BioCondition biocondition : biocondition_list) { String newID = dao_instance.getNextObjectID(null); BLOCKED_IDs.add(newID); biocondition.setBioConditionID(newID); //THE biocondition ID SHOULD BE UPDATED IN ALL THE BIOREPLICATES dao_instance.insert(biocondition); } /** * ******************************************************* * STEP 4 COMMIT CHANGES TO DATABASE. throws SQLException IF * ERROR --> throws SQL Exception, GO TO STEP 5b ELSE --> GO TO * STEP 5 * ******************************************************* */ dao_instance.doCommit(); } catch (Exception e) { ServerErrorManager.handleException(e, Samples_servlets.class.getName(), "send_biocondition_template_document_handler", e.getMessage()); } finally { /** * ******************************************************* * STEP 5b CATCH ERROR, CLEAN CHANGES. throws SQLException * ******************************************************* */ if (ServerErrorManager.errorStatus()) { response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); if (ROLLBACK_NEEDED) { dao_instance.doRollback(); } } else { response.getWriter().print("{success: " + true + "}"); } for (String blocked_id : BLOCKED_IDs) { BlockedElementsManager.getBlockedElementsManager().unlockID(blocked_id); } /** * ******************************************************* * STEP 6 Close connection. * ******************************************************** */ if (dao_instance != null) { dao_instance.closeConnection(); } } //CATCH IF THE ERROR OCCURRED IN ROLL BACK OR CONNECTION CLOSE } catch (Exception e) { ServerErrorManager.handleException(e, Samples_servlets.class.getName(), "send_xls_creation_document_handler", e.getMessage()); response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); } }
From source file:servlets.updatePhoto.java
private String uploadImage(HttpServletRequest request) throws FileUploadException, Exception { String url = ""; String imgDir = config.getServletContext().getRealPath("/images/") + "/"; File dir = new File(imgDir); dir.mkdirs();/*from w ww .jav a2s . co m*/ DiskFileItemFactory fabrica = new DiskFileItemFactory(); fabrica.setSizeThreshold(1024); fabrica.setRepository(dir); ServletFileUpload upload = new ServletFileUpload(fabrica); List<FileItem> partes = upload.parseRequest(request); for (FileItem item : partes) { System.out.println("Subiendo"); File archivo = new File(imgDir, item.getName()); item.write(archivo); url = item.getName(); } return url; }
From source file:servlets.UploadServlet2.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.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;/*from w w w .jav a2s .co m*/ } 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(filePath)); // 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>"); response.sendRedirect("admin.jsp"); } catch (Exception ex) { System.out.println(ex); } }
From source file:servletServices.serviceFile.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*ww w . j av a 2 s. com*/ * * @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 { HttpSession session = request.getSession(); int pkStudent = 0; if (session.getAttribute("pkStudent") != null) { pkStudent = Integer.parseInt(session.getAttribute("pkStudent").toString()); } if (request.getParameter("update") != null) { String field_name = request.getParameter("update"); String field_value; try (PrintWriter out = response.getWriter()) { if (session.getAttribute("pkStudent") != null) { File file; int maxFileSize = 5000 * 1024 * 50; int maxMemSize = 5000 * 1024 * 50; // Verify the content type String contentType = request.getContentType(); if ((contentType.contains("multipart/form-data"))) { DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. // Path String enrollment = session.getAttribute("enrollmentStudent").toString(); String path = "C:/temp/" + enrollment; File filePath = new File(path); if (filePath.exists()) { factory.setRepository(filePath); } else { filePath.mkdirs(); factory.setRepository(filePath); } // 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(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if (sizeInBytes <= 1048576) { field_value = field_name.replace("fl_", ""); if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + "/" + field_value + ".pdf"); } else { file = new File(filePath + "/" + field_value + ".pdf"); //file = new File( filePath +"/"+ fileName.substring(fileName.lastIndexOf("\\")+1)); } fi.write(file); //out.println("Archivo cargado en " +filePath +""); //Establecer los parametros a la BD if (new studentControl() .UpdateStudent(pkStudent, field_name, (path + "/" + field_value + ".pdf")) .equals("Datos Modificados")) { out.print("Cargado"); } else { out.print("Fail"); } } else { out.print("File much long"); } } } } catch (Exception ex) { out.println(ex); } } else { out.println("<p>No existe un archivo en este campo</p>"); } } else { response.sendRedirect("siut/alumnos.jsp"); } } } if (request.getParameter("viewFile") != null) { try (ServletOutputStream out = response.getOutputStream()) { String fileType = request.getParameter("viewFile"); String enrollment = session.getAttribute("enrollmentStudent").toString(); if (enrollment != null) { String pdfPath = "C://temp/" + enrollment + "/" + fileType + ".pdf"; File existFile = new File(pdfPath); if (existFile.exists()) { ServletOutputStream outs = response.getOutputStream(); response.setContentType("application/pdf"); File file = new File(pdfPath); response.setHeader("Content-disposition", "inline; filename=" + enrollment + "-" + fileType + ".pdf"); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { InputStream isr = new FileInputStream(file); bis = new BufferedInputStream(isr); bos = new BufferedOutputStream(outs); byte[] buff = new byte[2048]; int bytesRead; // Simple read/write loop. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (Exception e) { response.setContentType("text/html;charset=UTF-8"); out.println("Exception ----- Message ---" + e); } finally { if (bis != null) bis.close(); if (bos != null) bos.close(); } } else { response.setContentType("text/html;charset=UTF-8"); out.print("Lo sentimos no se encuentra el archivo :("); } } else { response.sendRedirect("siut/alumnos.jsp"); } } } //Load files of databases binary /*if(request.getParameter("viewFile")!=null){ try(ServletOutputStream out = response.getOutputStream()){ String file=request.getParameter("viewFile"); byte[] pdfFile; pdfFile =new studentControl().SelectFile(file, pkStudent); if((pdfFile.length>0)){ response.setContentType("application/pdf"); out.write(pdfFile); }else{ out.print("<h1>No Hay Archivo en la Base de Datos</h1>"); } if(Arrays.toString(pdfFile).equals("null")){ out.print("<h1>Parametros incorrectos!</h1>"); } } }*/ }
From source file:sfs.pages.beans.FaqAbmBean.java
public void upload() { FileItem file = null;/*from w w w . j ava2s . com*/ try { HttpServletRequest servletRequest = (HttpServletRequest) FacesContext.getCurrentInstance() .getExternalContext().getRequest(); ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext() .getContext(); DiskFileItemFactory factory = new DiskFileItemFactory(); File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); factory.setRepository(repository); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(servletRequest); if (items != null && !items.isEmpty()) { file = items.get(0); } } catch (Exception ex) { Utilities.printToLog("Error al cargar el archivo", ex, Utilities.LOG_LEVEL_ERROR); } if (file != null) { if (uploadedFiles == null) { uploadedFiles = new ArrayList<UploadedFile>(); } try { int r = (int) (Math.random() * 100000); String finalName = r + "_" + file.getName(); String fullPath = TextResourcesUtil.getText("uploadpath") + File.separator + finalName; String uri = "./sfile/" + finalName; File f = new File(fullPath); Utilities.copyData(file.getInputStream(), new FileOutputStream(f)); UploadedFile uf = new UploadedFile(); uf.setDescription(file.getName()); uf.setFilesize((int) file.getSize()); uf.setName(file.getName()); uf.setPath(uri); uploadedFiles.add(uf); FacesMessage msg = new FacesMessage("Succesful", file.getName() + " is uploaded."); FacesContext.getCurrentInstance().addMessage(null, msg); } catch (Exception e) { addMessage("Error " + file.getName() + " not uploaded.", e.getMessage()); } } }