List of usage examples for org.apache.commons.fileupload FileItem delete
void delete();
From source file:cn.edu.hbcit.servlets.ConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * /*from www. j a v a 2 s . c om*/ * The servlet accepts commands sent in the following format:<br /> * <code>connector?Command=<FileUpload>&Type=<ResourceType>&CurrentFolder=<FolderPath></code> * with the file in the <code>POST</code> body.<br /> * <br> * It stores an uploaded file (renames a file if another exists with the * same name) and then returns the JavaScript callback. */ @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Entering Connector#doPost"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); logger.debug("Parameter Command: {}", commandStr); logger.debug("Parameter Type: {}", typeStr); logger.debug("Parameter CurrentFolder: {}", currentFolderStr); UploadResponse ur; // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr' // are empty if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) { commandStr = "QuickUpload"; currentFolderStr = "/"; } if (!RequestCycleHandler.isEnabledForFileUpload(request)) ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null, Messages.NOT_AUTHORIZED_FOR_UPLOAD); else if (!CommandHandler.isValidForPost(commandStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND); else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE); else if (!UtilsFile.isValidPath(currentFolderStr)) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr); String typePath = UtilsFile.constructServerSidePath(request, resourceType); String typeDirPath = getServletContext().getRealPath(typePath); File typeDir = new File(typeDirPath); UtilsFile.checkDirAndCreate(typeDir); File currentDir = new File(typeDir, currentFolderStr); if (!currentDir.exists()) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { String newFilename = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); FileOperate fo = new FileOperate();//liwei (+ ) upload.setHeaderEncoding("UTF-8");//liwei try { List<FileItem> items = upload.parseRequest(request); // We upload only one file at the same time FileItem uplFile = items.get(0); String rawName = UtilsFile.sanitizeFileName(uplFile.getName()); String filename = FilenameUtils.getName(rawName); String oldName = FilenameUtils.getName(rawName); String baseName = FilenameUtils.removeExtension(filename); String extension = FilenameUtils.getExtension(filename); filename = fo.generateRandomFilename() + extension;//liwei (+ ) //filename = UUID.randomUUID().toString()+"."+extension;//liwei (UUID) logger.warn("" + oldName + "" + filename + ""); if (!ExtensionsHandler.isAllowed(resourceType, extension)) ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); else { // construct an unique file name File pathToSave = new File(currentDir, filename); int counter = 1; while (pathToSave.exists()) { newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")") .concat(".").concat(extension); pathToSave = new File(currentDir, newFilename); counter++; } if (Utils.isEmpty(newFilename)) ur = new UploadResponse(UploadResponse.SC_OK, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(filename)); else ur = new UploadResponse(UploadResponse.SC_RENAMED, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(newFilename), newFilename); // secure image check if (resourceType.equals(ResourceTypeHandler.IMAGE) && ConnectorHandler.isSecureImageUploads()) { if (UtilsFile.isImage(uplFile.getInputStream())) uplFile.write(pathToSave); else { uplFile.delete(); ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } } else uplFile.write(pathToSave); } } catch (Exception e) { ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR); } } } out.print(ur); out.flush(); out.close(); logger.debug("Exiting Connector#doPost"); }
From source file:com.zlk.fckeditor.Dispatcher.java
/** * Called by the connector servlet to handle a {@code POST} request. In * particular, it handles the {@link Command#FILE_UPLOAD FileUpload} and * {@link Command#QUICK_UPLOAD QuickUpload} commands. * /*from ww w. j a v a2s . c om*/ * @param request * the current request instance * @return the upload response instance associated with this request */ UploadResponse doPost(final HttpServletRequest request) { logger.debug("Entering Dispatcher#doPost"); Context context = ThreadLocalData.getContext(); context.logBaseParameters(); UploadResponse uploadResponse = null; // check permissions for user actions if (!RequestCycleHandler.isFileUploadEnabled(request)) uploadResponse = UploadResponse.getFileUploadDisabledError(); // check parameters else if (!Command.isValidForPost(context.getCommandStr())) uploadResponse = UploadResponse.getInvalidCommandError(); else if (!ResourceType.isValidType(context.getTypeStr())) uploadResponse = UploadResponse.getInvalidResourceTypeError(); else if (!UtilsFile.isValidPath(context.getCurrentFolderStr())) uploadResponse = UploadResponse.getInvalidCurrentFolderError(); else { // call the Connector#fileUpload ResourceType type = context.getDefaultResourceType(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> items = upload.parseRequest(request); // We upload just one file at the same time FileItem uplFile = items.get(0); // Some browsers transfer the entire source path not just the // filename String fileName = FilenameUtils.getName(uplFile.getName()); logger.debug("Parameter NewFile: {}", fileName); // ?? if (uplFile.getSize() > 1024 * 1024 * 50) {//50M // ? uploadResponse = new UploadResponse(204); } else { //??uuid? String extension = FilenameUtils.getExtension(fileName); fileName = UUID.randomUUID().toString() + "." + extension; /* String path=request.getSession().getServletContext().getRealPath("/")+"userfiles/"; fileName = makeFileName(path+"/"+type.getPath(), fileName);*/ logger.debug("Change FileName to UUID: {} (by zhoulukang)", fileName); // check the extension if (type.isDeniedExtension(FilenameUtils.getExtension(fileName))) uploadResponse = UploadResponse.getInvalidFileTypeError(); // Secure image check (can't be done if QuickUpload) else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads() && !UtilsFile.isImage(uplFile.getInputStream())) { uploadResponse = UploadResponse.getInvalidFileTypeError(); } else { String sanitizedFileName = UtilsFile.sanitizeFileName(fileName); logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName); String newFileName = connector.fileUpload(type, context.getCurrentFolderStr(), sanitizedFileName, uplFile.getInputStream()); String fileUrl = UtilsResponse.fileUrl(RequestCycleHandler.getUserFilesPath(request), type, context.getCurrentFolderStr(), newFileName); if (sanitizedFileName.equals(newFileName)) uploadResponse = UploadResponse.getOK(fileUrl); else { uploadResponse = UploadResponse.getFileRenamedWarning(fileUrl, newFileName); logger.debug("Parameter NewFile (renamed): {}", newFileName); } } uplFile.delete(); } } catch (InvalidCurrentFolderException e) { uploadResponse = UploadResponse.getInvalidCurrentFolderError(); } catch (WriteException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } catch (IOException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } catch (FileUploadException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } } logger.debug("Exiting Dispatcher#doPost"); return uploadResponse; }
From source file:com.jl.common.ConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * /*from w w w. j a va2s .c om*/ * The servlet accepts commands sent in the following format:<br /> * <code>connector?Command=<FileUpload>&Type=<ResourceType>&CurrentFolder=<FolderPath></code> * with the file in the <code>POST</code> body.<br /> * <br> * It stores an uploaded file (renames a file if another exists with the * same name) and then returns the JavaScript callback. */ @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Entering Connector#doPost"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); logger.debug("Parameter Command: {}", commandStr); logger.debug("Parameter Type: {}", typeStr); logger.debug("Parameter CurrentFolder: {}", currentFolderStr); UploadResponse ur; // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr' // are empty if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) { commandStr = "QuickUpload"; currentFolderStr = "/"; } if (!RequestCycleHandler.isEnabledForFileUpload(request)) ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null, Messages.NOT_AUTHORIZED_FOR_UPLOAD); else if (!CommandHandler.isValidForPost(commandStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND); else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE); else if (!UtilsFile.isValidPath(currentFolderStr)) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr); String typePath = UtilsFile.constructServerSidePath(request, resourceType); String typeDirPath = getServletContext().getRealPath(typePath); File typeDir = new File(typeDirPath); UtilsFile.checkDirAndCreate(typeDir); File currentDir = new File(typeDir, currentFolderStr); if (!currentDir.exists()) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { String newFilename = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8");// try { List<FileItem> items = upload.parseRequest(request); // We upload only one file at the same time FileItem uplFile = items.get(0); String rawName = UtilsFile.sanitizeFileName(uplFile.getName()); String filename = FilenameUtils.getName(rawName); String baseName = FilenameUtils.removeExtension(filename); String extension = FilenameUtils.getExtension(filename); filename = UUID.randomUUID().toString() + "." + extension;// // if (!ExtensionsHandler.isAllowed(resourceType, extension)) { ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } // else if (uplFile.getSize() > 50 * 1024) { // ur = new UploadResponse(204); } // else { // construct an unique file name File pathToSave = new File(currentDir, filename); int counter = 1; while (pathToSave.exists()) { newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")") .concat(".").concat(extension); pathToSave = new File(currentDir, newFilename); counter++; } if (Utils.isEmpty(newFilename)) ur = new UploadResponse(UploadResponse.SC_OK, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(filename)); else ur = new UploadResponse(UploadResponse.SC_RENAMED, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(newFilename), newFilename); // secure image check if (resourceType.equals(ResourceTypeHandler.IMAGE) && ConnectorHandler.isSecureImageUploads()) { if (UtilsFile.isImage(uplFile.getInputStream())) uplFile.write(pathToSave); else { uplFile.delete(); ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } } else uplFile.write(pathToSave); } } catch (Exception e) { ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR); } } } out.print(ur); out.flush(); out.close(); logger.debug("Exiting Connector#doPost"); }
From source file:edu.harvard.hul.ois.drs.pdfaconvert.service.servlets.PdfaConverterServlet.java
/** * Handles the file upload for PdfaConverter processing via streaming of the file * using the <code>POST</code> method. Example: curl -X POST -F datafile=@ * <path/to/file> <host>:[<port>]/pdfa-converter/examine Note: "pdfa-converter" in the above URL * needs to be adjusted to the final name of the WAR file. * * @param request/*from ww w.j a va2 s .c om*/ * servlet request * @param response * servlet response * @throws ServletException * if a servlet-specific error occurs * @throws IOException * if an I/O error occurs */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.info("Entering doPost()"); if (!ServletFileUpload.isMultipartContent(request)) { ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_BAD_REQUEST, " Missing Multipart Form Data. ", request.getRequestURL().toString()); sendErrorMessageResponse(errorMessage, response); return; } try { List<FileItem> formItems = upload.parseRequest(request); Iterator<FileItem> iter = formItems.iterator(); // iterates over form's fields while (iter.hasNext()) { FileItem item = iter.next(); // processes only fields that are not form fields // if (!item.isFormField()) { if (!item.isFormField() && item.getFieldName().equals(FORM_FIELD_DATAFILE)) { long fileSize = item.getSize(); if (fileSize < 1) { ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_BAD_REQUEST, " Missing File Data. ", request.getRequestURL().toString()); sendErrorMessageResponse(errorMessage, response); return; } // save original uploaded file name InputStream inputStream = item.getInputStream(); String origFileName = item.getName(); DiskFileItemExt itemExt = new DiskFileItemExt(item.getFieldName(), item.getContentType(), item.isFormField(), item.getName(), (maxInMemoryFileSizeMb * (int) MB_MULTIPLIER), factory.getRepository()); // Create a temporary unique filename for a file containing the original temp filename plus the real filename containing its file type suffix. String tempFilename = itemExt.getTempFile().getName(); StringBuilder realFileTypeFilename = new StringBuilder(tempFilename); realFileTypeFilename.append('-'); realFileTypeFilename.append(origFileName); // create the file in the same temporary directory File realInputFile = new File(factory.getRepository(), realFileTypeFilename.toString()); // strip out suffix before saving to ServletRequestListener request.setAttribute(TEMP_FILE_NAME_KEY, tempFilename.substring(0, tempFilename.indexOf('.'))); // turn InputStream into a File in temp directory OutputStream outputStream = new FileOutputStream(realInputFile); IOUtils.copy(inputStream, outputStream); outputStream.close(); try { // Send it to the PdfaConverter processor... sendPdfaConverterExamineResponse(realInputFile, origFileName, request, response); } finally { // delete both original temporary file -- if large enough will have been persisted to disk -- and our created file if (!item.isInMemory()) { // item.delete(); } if (realInputFile.exists()) { realInputFile.delete(); } } } else { ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_BAD_REQUEST, " The request did not have the correct name attribute of \"datafile\" in the form processing. ", request.getRequestURL().toString(), " Processing halted."); sendErrorMessageResponse(errorMessage, response); return; } } } catch (FileUploadException ex) { logger.error(ex); ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, " There was an unexpected server error: " + ex.getMessage(), request.getRequestURL().toString(), " Processing halted."); sendErrorMessageResponse(errorMessage, response); return; } }
From source file:com.lecheng.cms.servlet.ConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * /*from w ww. j a va2s . co m*/ * The servlet accepts commands sent in the following format:<br /> * <code>connector?Command=<FileUpload>&Type=<ResourceType>&CurrentFolder=<FolderPath></code> * with the file in the <code>POST</code> body.<br /> * <br> * It stores an uploaded file (renames a file if another exists with the * same name) and then returns the JavaScript callback. */ @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // logger.debug("Entering Connector#doPost"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); // logger.debug("Parameter Command: {}", commandStr); // logger.debug("Parameter Type: {}", typeStr); // logger.debug("Parameter CurrentFolder: {}", currentFolderStr); UploadResponse ur; // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr' // are empty if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) { commandStr = "QuickUpload"; currentFolderStr = "/"; } if (!RequestCycleHandler.isEnabledForFileUpload(request)) ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null, Messages.NOT_AUTHORIZED_FOR_UPLOAD); else if (!CommandHandler.isValidForPost(commandStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND); else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE); else if (!UtilsFile.isValidPath(currentFolderStr)) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr); String typePath = UtilsFile.constructServerSidePath(request, resourceType); String typeDirPath = getServletContext().getRealPath(typePath); File typeDir = new File(typeDirPath); UtilsFile.checkDirAndCreate(typeDir); File currentDir = new File(typeDir, currentFolderStr); if (!currentDir.exists()) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { String newFilename = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // FileOperate fo = new FileOperate();//liwei // (+ ) upload.setHeaderEncoding("UTF-8");// liwei try { List<FileItem> items = upload.parseRequest(request); // We upload only one file at the same time FileItem uplFile = items.get(0); String rawName = UtilsFile.sanitizeFileName(uplFile.getName()); String filename = FilenameUtils.getName(rawName); String oldName = FilenameUtils.getName(rawName); String baseName = FilenameUtils.removeExtension(filename); String extension = FilenameUtils.getExtension(filename); // filename = fo.generateRandomFilename() + // extension;//liwei // (+ ) filename = UUID.randomUUID().toString() + "." + extension;// liwei // (UUID) // logger.warn(""+oldName+""+filename+""); if (!ExtensionsHandler.isAllowed(resourceType, extension)) ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); else { // construct an unique file name File pathToSave = new File(currentDir, filename); int counter = 1; while (pathToSave.exists()) { newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")") .concat(".").concat(extension); pathToSave = new File(currentDir, newFilename); counter++; } if (Utils.isEmpty(newFilename)) ur = new UploadResponse(UploadResponse.SC_OK, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(filename)); else ur = new UploadResponse(UploadResponse.SC_RENAMED, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(newFilename), newFilename); // secure image check if (resourceType.equals(ResourceTypeHandler.IMAGE) && ConnectorHandler.isSecureImageUploads()) { if (UtilsFile.isImage(uplFile.getInputStream())) uplFile.write(pathToSave); else { uplFile.delete(); ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } } else uplFile.write(pathToSave); } } catch (Exception e) { ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR); } } } out.print(ur); out.flush(); out.close(); // logger.debug("Exiting Connector#doPost"); }
From source file:com.socialization.util.ConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * //from www . j a v a 2s . co m * The servlet accepts commands sent in the following format:<br /> * <code>connector?Command=<FileUpload>&Type=<ResourceType>&CurrentFolder=<FolderPath></code> * with the file in the <code>POST</code> body.<br /> * <br> * It stores an uploaded file (renames a file if another exists with the same name) and then * returns the JavaScript callback. */ @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Entering Connector#doPost"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); logger.debug("Parameter Command: {}", commandStr); logger.debug("Parameter Type: {}", typeStr); logger.debug("Parameter CurrentFolder: {}", currentFolderStr); UploadResponse ur; // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr' // are empty if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) { commandStr = "QuickUpload"; currentFolderStr = "/"; } if (!RequestCycleHandler.isEnabledForFileUpload(request)) ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null, Messages.NOT_AUTHORIZED_FOR_UPLOAD); else if (!CommandHandler.isValidForPost(commandStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND); else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE); else if (!UtilsFile.isValidPath(currentFolderStr)) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr); String typeDirPath = null; if ("File".equals(typeStr)) { // ${application.path}/WEB-INF/userfiles/ typeDirPath = getServletContext().getRealPath("WEB-INF/userfiles/"); } else { String typePath = UtilsFile.constructServerSidePath(request, resourceType); typeDirPath = getServletContext().getRealPath(typePath); } File typeDir = new File(typeDirPath); UtilsFile.checkDirAndCreate(typeDir); File currentDir = new File(typeDir, currentFolderStr); if (!currentDir.exists()) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { String newFilename = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); try { List<FileItem> items = upload.parseRequest(request); // We upload only one file at the same time FileItem uplFile = items.get(0); String rawName = UtilsFile.sanitizeFileName(uplFile.getName()); String filename = FilenameUtils.getName(rawName); String baseName = FilenameUtils.removeExtension(filename); String extension = FilenameUtils.getExtension(filename); // ???? if (!ExtensionsHandler.isAllowed(resourceType, extension)) { ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } // ?? else if (uplFile.getSize() > 1024 * 1024 * 3) { // ? ur = new UploadResponse(204); } // ?, ? else { // construct an unique file name // UUID ???, ? filename = UUID.randomUUID().toString() + "." + extension; filename = makeFileName(currentDir.getPath(), filename); File pathToSave = new File(currentDir, filename); int counter = 1; while (pathToSave.exists()) { newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")") .concat(".").concat(extension); pathToSave = new File(currentDir, newFilename); counter++; } if (Utils.isEmpty(newFilename)) ur = new UploadResponse(UploadResponse.SC_OK, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(filename)); else ur = new UploadResponse(UploadResponse.SC_RENAMED, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(newFilename), newFilename); // secure image check if (resourceType.equals(ResourceTypeHandler.IMAGE) && ConnectorHandler.isSecureImageUploads()) { if (UtilsFile.isImage(uplFile.getInputStream())) uplFile.write(pathToSave); else { uplFile.delete(); ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } } else uplFile.write(pathToSave); } } catch (Exception e) { ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR); } } } out.print(ur); out.flush(); out.close(); logger.debug("Exiting Connector#doPost"); }
From source file:edu.umd.cs.submitServer.filters.RegisterStudentsFilter.java
@Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; if (!request.getMethod().equals("POST")) { throw new ServletException("Only POST accepted"); }/*from w w w . j a v a 2s.c om*/ Connection conn = null; BufferedReader reader = null; FileItem fileItem = null; TreeSet<StudentRegistration> registeredStudents = new TreeSet<StudentRegistration>(); List<String> errors = new ArrayList<String>(); try { conn = getConnection(); // MultipartRequestFilter is required MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST); Course course = (Course) request.getAttribute("course"); // open the uploaded file fileItem = multipartRequest.getFileItem(); reader = new BufferedReader(new InputStreamReader(fileItem.getInputStream())); int lineNumber = 1; while (true) { String line = reader.readLine(); if (line == null) break; lineNumber++; // hard-coded skip of first two lines for Maryland-specific // format if (line.startsWith("Last,First,UID,section,ClassAcct,DirectoryID")) continue; if (line.startsWith(",,,,,")) { if (line.equals(",,,,,")) continue; String ldap = line.substring(5); Student student = Student.lookupByLoginName(ldap, conn); if (student != null) { StudentRegistration sr = StudentForUpload.registerStudent(course, student, "", ldap, null, conn); registeredStudents.add(sr); } else errors.add("Did not find " + ldap); continue; } if (line.startsWith("#")) continue; // skip blank lines if (line.trim().equals("")) continue; try { StudentForUpload s = new StudentForUpload(line, delimiter); Student student = s.lookupOrInsert(conn); StudentRegistration sr = StudentForUpload.registerStudent(course, student, s.section, s.classAccount, null, conn); registeredStudents.add(sr); } catch (IllegalStateException e) { errors.add(e.getMessage()); ServletExceptionFilter.logError(conn, ServerError.Kind.EXCEPTION, request, "error while registering " + line, null, e); } catch (Exception e1) { errors.add("Problem processing line: '" + line + "' at line number: " + lineNumber); ServletExceptionFilter.logError(conn, ServerError.Kind.EXCEPTION, request, "error while registering " + line, null, e1); } } } catch (SQLException e) { throw new ServletException(e); } finally { releaseConnection(conn); if (reader != null) reader.close(); if (fileItem != null) fileItem.delete(); } request.setAttribute("registeredStudents", registeredStudents); request.setAttribute("errors", errors); chain.doFilter(request, response); }
From source file:com.shangde.common.util.FCKConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * /*from w ww .ja v a2 s .c om*/ * The servlet accepts commands sent in the following format:<br /> * <code>connector?Command=<FileUpload>&Type=<ResourceType>&CurrentFolder=<FolderPath></code> * with the file in the <code>POST</code> body.<br /> * <br> * It stores an uploaded file (renames a file if another exists with the * same name) and then returns the JavaScript callback. */ @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Entering Connector#doPost"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); logger.debug("Parameter Command: {}", commandStr); logger.debug("Parameter Type: {}", typeStr); logger.debug("Parameter CurrentFolder: {}", currentFolderStr); UploadResponse ur; // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr' // are empty if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) { commandStr = "QuickUpload"; currentFolderStr = "/"; } if (!RequestCycleHandler.isEnabledForFileUpload(request)) ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null, Messages.NOT_AUTHORIZED_FOR_UPLOAD); else if (!CommandHandler.isValidForPost(commandStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND); else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE); else if (!UtilsFile.isValidPath(currentFolderStr)) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr); String typePath = null; String typeDirPath = null; String otherFilePath = this.getServletConfig().getServletContext().getRealPath("/"); System.out.println("===========" + otherFilePath); String fckSavePath = (String) request.getSession().getAttribute("fckSavePath"); if (fckSavePath != null && !fckSavePath.trim().equals("")) { typeDirPath = otherFilePath + "/upload/" + fckSavePath + "/"; } else { typeDirPath = otherFilePath + "/upload/public/"; } // if("article".equals((request.getSession().getAttribute("fckSavePath")))){//? feceditor.properties // typeDirPath = otherFilePath + "/static/images/"; // }else if("exam".equals((request.getSession().getAttribute("exam")))){//? feceditor.properties // typeDirPath = otherFilePath + "/static/images/"; // } // else{ // typeDirPath = otherFilePath + "/back/upload/fckimage/"; // } File typeDir = new File(typeDirPath); UtilsFile.checkDirAndCreate(typeDir); File currentDir = new File(typeDir, currentFolderStr); if (!currentDir.exists()) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { String newFilename = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> items = upload.parseRequest(request); // We upload only one file at the same time, FileItem uplFile = items.get(0); String rawName = UtilsFile.sanitizeFileName(uplFile.getName()); String filename = FilenameUtils.getName(rawName); String baseName = FilenameUtils.removeExtension(filename); String extension = FilenameUtils.getExtension(filename); filename = UUID.randomUUID() + "." + extension;// if (!ExtensionsHandler.isAllowed(resourceType, extension)) ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); else { // construct an unique file name File pathToSave = new File(currentDir, filename); int counter = 1; while (pathToSave.exists()) {//???? newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")") .concat(".").concat(extension); pathToSave = new File(currentDir, newFilename); counter++; } if (Utils.isEmpty(newFilename)) {//???? if (fckSavePath != null && !fckSavePath.trim().equals("")) { String temp = "http://import.highso.org.cn/upload" + "/" + fckSavePath + "/" + filename; ur = new UploadResponse(UploadResponse.SC_OK, temp); } else { String temp = "http://import.highso.org.cn/upload/public/" + filename; ur = new UploadResponse(UploadResponse.SC_OK, temp); } } else {//???? if (fckSavePath != null && !fckSavePath.trim().equals("")) { String temp = "http://import.highso.org.cn/upload" + "/" + fckSavePath + "/" + filename; ur = new UploadResponse(UploadResponse.SC_RENAMED, temp); } else { String temp = "http://import.highso.org.cn/upload/public/" + filename; ur = new UploadResponse(UploadResponse.SC_RENAMED, temp); } } // secure image check if (resourceType.equals(ResourceTypeHandler.IMAGE) && ConnectorHandler.isSecureImageUploads()) { if (UtilsFile.isImage(uplFile.getInputStream())) uplFile.write(pathToSave); else { uplFile.delete(); ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } } else uplFile.write(pathToSave); } } catch (Exception e) { logger.error(e.getMessage()); ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR); } } } out.print(ur); out.flush(); out.close(); logger.debug("Exiting Connector#doPost"); }
From source file:com.mx.nibble.middleware.web.util.FileUpload.java
public void performTask(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) { /**/*from w ww . j a v a 2s. com*/ * This pages gives a sample of java upload management. It needs the commons FileUpload library, which can be found on apache.org. * * Note: * - putting error=true as a parameter on the URL will generate an error. Allows test of upload error management in the applet. * * * * * * */ logger.debug(" Directory to store all the uploaded files"); String ourTempDirectory = "/opt/erp/import/obras/"; try { out = response.getWriter(); } catch (Exception e) { e.printStackTrace(); } byte[] cr = { 13 }; byte[] lf = { 10 }; String CR = new String(cr); String LF = new String(lf); String CRLF = CR + LF; out.println("Before a LF=chr(10)" + LF + "Before a CR=chr(13)" + CR + "Before a CRLF" + CRLF); logger.debug("Initialization for chunk management."); boolean bLastChunk = false; int numChunk = 0; logger.debug( "CAN BE OVERRIDEN BY THE postURL PARAMETER: if error=true is passed as a parameter on the URL"); boolean generateError = false; boolean generateWarning = false; boolean sendRequest = false; response.setContentType("text/plain"); java.util.Enumeration<String> headers = request.getHeaderNames(); out.println("[parseRequest.jsp] ------------------------------ "); out.println("[parseRequest.jsp] Headers of the received request:"); logger.debug("[parseRequest.jsp] Headers of the received request:"); while (headers.hasMoreElements()) { String header = headers.nextElement(); out.println("[parseRequest.jsp] " + header + ": " + request.getHeader(header)); logger.debug("[parseRequest.jsp] " + header + ": " + request.getHeader(header)); } out.println("[parseRequest.jsp] ------------------------------ "); try { logger.debug(" Get URL Parameters."); Enumeration paraNames = request.getParameterNames(); out.println("[parseRequest.jsp] ------------------------------ "); out.println("[parseRequest.jsp] Parameters: "); logger.debug("[parseRequest.jsp] Parameters: "); String pname; String pvalue; while (paraNames.hasMoreElements()) { pname = (String) paraNames.nextElement(); pvalue = request.getParameter(pname); out.println("[parseRequest.jsp] " + pname + " = " + pvalue); logger.debug("[parseRequest.jsp] " + pname + " = " + pvalue); if (pname.equals("jufinal")) { bLastChunk = pvalue.equals("1"); } else if (pname.equals("jupart")) { numChunk = Integer.parseInt(pvalue); } if (pname.equals("error") && pvalue.equals("true")) { generateError = true; logger.debug( "For debug convenience, putting error=true as a URL parameter, will generate an error in this response."); } if (pname.equals("warning") && pvalue.equals("true")) { generateWarning = true; logger.debug( "For debug convenience, putting warning=true as a URL parameter, will generate a warning in this response."); } if (pname.equals("sendRequest") && pvalue.equals("true")) { sendRequest = true; logger.debug( "For debug convenience, putting readRequest=true as a URL parameter, will send back the request content into the response of this page."); } } out.println("[parseRequest.jsp] ------------------------------ "); int ourMaxMemorySize = 10000000; int ourMaxRequestSize = 2000000000; /////////////////////////////////////////////////////////////////////////////////////////////////////// //The code below is directly taken from the jakarta fileupload common classes //All informations, and download, available here : http://jakarta.apache.org/commons/fileupload/ /////////////////////////////////////////////////////////////////////////////////////////////////////// logger.debug(" Create a factory for disk-based file items"); DiskFileItemFactory factory = new DiskFileItemFactory(); logger.debug(" Set factory constraints"); factory.setSizeThreshold(ourMaxMemorySize); logger.debug("ourTempDirectory" + ourTempDirectory); factory.setRepository(new File(ourTempDirectory)); logger.debug(" Create a new file upload handler"); ServletFileUpload upload = new ServletFileUpload(factory); logger.debug(" Set overall request size constraint"); upload.setSizeMax(ourMaxRequestSize); logger.debug(" Parse the request"); if (sendRequest) { logger.debug("For debug only. Should be removed for production systems. "); out.println( "[parseRequest.jsp] ==========================================================================="); out.println("[parseRequest.jsp] Sending the received request content: "); logger.debug("[parseRequest.jsp] Sending the received request content: "); InputStream is = request.getInputStream(); int c; while ((c = is.read()) >= 0) { out.write(c); } logger.debug("while"); is.close(); out.println( "[parseRequest.jsp] ==========================================================================="); } else if (!request.getContentType().startsWith("multipart/form-data")) { out.println("[parseRequest.jsp] No parsing of uploaded file: content type is " + request.getContentType()); } else { List /* FileItem */ items = upload.parseRequest(request); logger.debug(" Process the uploaded items" + items.size()); Iterator iter = items.iterator(); FileItem fileItem; File fout; out.println("[parseRequest.jsp] Let's read the sent data (" + items.size() + " items)"); while (iter.hasNext()) { fileItem = (FileItem) iter.next(); if (fileItem.isFormField()) { out.println("[parseRequest.jsp] (form field) " + fileItem.getFieldName() + " = " + fileItem.getString()); logger.debug( "If we receive the md5sum parameter, we've read finished to read the current file. It's not"); logger.debug( "a very good (end of file) signal. Will be better in the future ... probably !"); logger.debug("Let's put a separator, to make output easier to read."); if (fileItem.getFieldName().equals("md5sum[]")) { out.println("[parseRequest.jsp] ------------------------------ "); } } else { logger.debug("Ok, we've got a file. Let's process it."); logger.debug("Again, for all informations of what is exactly a FileItem, please"); logger.debug("have a look to http://jakarta.apache.org/commons/fileupload/"); out.println("[parseRequest.jsp] FieldName: " + fileItem.getFieldName()); out.println("[parseRequest.jsp] File Name: " + fileItem.getName()); out.println("[parseRequest.jsp] ContentType: " + fileItem.getContentType()); out.println("[parseRequest.jsp] Size (Bytes): " + fileItem.getSize()); logger.debug( "If we are in chunk mode, we add .partN at the end of the file, where N is the chunk number."); String uploadedFilename = fileItem.getName() + (numChunk > 0 ? ".part" + numChunk : ""); fout = new File(ourTempDirectory + (new File(uploadedFilename)).getName()); out.println("[parseRequest.jsp] File Out: " + fout.toString()); logger.debug(" write the file"); fileItem.write(fout); // logger.debug("Chunk management: if it was the last chunk, let's recover the complete file"); logger.debug("by concatenating all chunk parts."); logger.debug(""); if (bLastChunk) { out.println("[parseRequest.jsp] Last chunk received: let's rebuild the complete file (" + fileItem.getName() + ")"); logger.debug("First: construct the final filename."); FileInputStream fis; FileOutputStream fos = new FileOutputStream(ourTempDirectory + fileItem.getName()); int nbBytes; byte[] byteBuff = new byte[1024]; String filename; for (int i = 1; i <= numChunk; i += 1) { filename = fileItem.getName() + ".part" + i; out.println("[parseRequest.jsp] " + " Concatenating " + filename); fis = new FileInputStream(ourTempDirectory + filename); while ((nbBytes = fis.read(byteBuff)) >= 0) { //out.println("[parseRequest.jsp] " + " Nb bytes read: " + nbBytes); fos.write(byteBuff, 0, nbBytes); } fis.close(); } fos.close(); } logger.debug(" End of chunk management"); // fileItem.delete(); } } logger.debug("while"); } if (generateWarning) { out.println("WARNING: just a warning message.\\nOn two lines!"); } out.println("[parseRequest.jsp] " + "Let's write a status, to finish the server response :"); logger.debug("Let's wait a little, to simulate the server time to manage the file."); Thread.sleep(500); logger.debug("Do you want to test a successful upload, or the way the applet reacts to an error ?"); if (generateError) { out.println( "ERROR: this is a test error (forced in /wwwroot/pages/parseRequest.jsp).\\nHere is a second line!"); } else { out.println("SUCCESS"); logger.debug(""); } out.println("[parseRequest.jsp] " + "End of server treatment "); } catch (Exception e) { out.println(""); out.println("ERROR: Exception e = " + e.toString()); out.println(""); } }
From source file:com.mx.nibble.middleware.web.util.FileParse.java
public String execute(ActionInvocation invocation) throws Exception { Iterator iterator = parameters.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry mapEntry = (Map.Entry) iterator.next(); System.out.println("The key is: " + mapEntry.getKey() + ",value is :" + mapEntry.getValue()); }//from ww w . ja v a2 s. c o m ActionContext ac = invocation.getInvocationContext(); HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST); HttpServletResponse response = (HttpServletResponse) ac.get(ServletActionContext.HTTP_RESPONSE); /** * This pages gives a sample of java upload management. It needs the commons FileUpload library, which can be found on apache.org. * * Note: * - putting error=true as a parameter on the URL will generate an error. Allows test of upload error management in the applet. * * * * * * */ // Directory to store all the uploaded files String ourTempDirectory = "/opt/erp/import/obras/"; byte[] cr = { 13 }; byte[] lf = { 10 }; String CR = new String(cr); String LF = new String(lf); String CRLF = CR + LF; System.out.println("Before a LF=chr(10)" + LF + "Before a CR=chr(13)" + CR + "Before a CRLF" + CRLF); //Initialization for chunk management. boolean bLastChunk = false; int numChunk = 0; //CAN BE OVERRIDEN BY THE postURL PARAMETER: if error=true is passed as a parameter on the URL boolean generateError = false; boolean generateWarning = false; boolean sendRequest = false; response.setContentType("text/plain"); java.util.Enumeration<String> headers = request.getHeaderNames(); System.out.println("[parseRequest.jsp] ------------------------------ "); System.out.println("[parseRequest.jsp] Headers of the received request:"); while (headers.hasMoreElements()) { String header = headers.nextElement(); System.out.println("[parseRequest.jsp] " + header + ": " + request.getHeader(header)); } System.out.println("[parseRequest.jsp] ------------------------------ "); try { // Get URL Parameters. Enumeration paraNames = request.getParameterNames(); System.out.println("[parseRequest.jsp] ------------------------------ "); System.out.println("[parseRequest.jsp] Parameters: "); String pname; String pvalue; while (paraNames.hasMoreElements()) { pname = (String) paraNames.nextElement(); pvalue = request.getParameter(pname); System.out.println("[parseRequest.jsp] " + pname + " = " + pvalue); if (pname.equals("jufinal")) { bLastChunk = pvalue.equals("1"); } else if (pname.equals("jupart")) { numChunk = Integer.parseInt(pvalue); } //For debug convenience, putting error=true as a URL parameter, will generate an error //in this response. if (pname.equals("error") && pvalue.equals("true")) { generateError = true; } //For debug convenience, putting warning=true as a URL parameter, will generate a warning //in this response. if (pname.equals("warning") && pvalue.equals("true")) { generateWarning = true; } //For debug convenience, putting readRequest=true as a URL parameter, will send back the request content //into the response of this page. if (pname.equals("sendRequest") && pvalue.equals("true")) { sendRequest = true; } } System.out.println("[parseRequest.jsp] ------------------------------ "); int ourMaxMemorySize = 10000000; int ourMaxRequestSize = 2000000000; /////////////////////////////////////////////////////////////////////////////////////////////////////// //The code below is directly taken from the jakarta fileupload common classes //All informations, and download, available here : http://jakarta.apache.org/commons/fileupload/ /////////////////////////////////////////////////////////////////////////////////////////////////////// // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setSizeThreshold(ourMaxMemorySize); factory.setRepository(new File(ourTempDirectory)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(ourMaxRequestSize); // Parse the request if (sendRequest) { //For debug only. Should be removed for production systems. System.out.println( "[parseRequest.jsp] ==========================================================================="); System.out.println("[parseRequest.jsp] Sending the received request content: "); InputStream is = request.getInputStream(); int c; while ((c = is.read()) >= 0) { out.write(c); } //while is.close(); System.out.println( "[parseRequest.jsp] ==========================================================================="); } else if (!request.getContentType().startsWith("multipart/form-data")) { System.out.println("[parseRequest.jsp] No parsing of uploaded file: content type is " + request.getContentType()); } else { List /* FileItem */ items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); FileItem fileItem; File fout; System.out.println("[parseRequest.jsp] Let's read the sent data (" + items.size() + " items)"); while (iter.hasNext()) { fileItem = (FileItem) iter.next(); if (fileItem.isFormField()) { System.out.println("[parseRequest.jsp] (form field) " + fileItem.getFieldName() + " = " + fileItem.getString()); //If we receive the md5sum parameter, we've read finished to read the current file. It's not //a very good (end of file) signal. Will be better in the future ... probably ! //Let's put a separator, to make output easier to read. if (fileItem.getFieldName().equals("md5sum[]")) { System.out.println("[parseRequest.jsp] ------------------------------ "); } } else { //Ok, we've got a file. Let's process it. //Again, for all informations of what is exactly a FileItem, please //have a look to http://jakarta.apache.org/commons/fileupload/ // System.out.println("[parseRequest.jsp] FieldName: " + fileItem.getFieldName()); System.out.println("[parseRequest.jsp] File Name: " + fileItem.getName()); System.out.println("[parseRequest.jsp] ContentType: " + fileItem.getContentType()); System.out.println("[parseRequest.jsp] Size (Bytes): " + fileItem.getSize()); //If we are in chunk mode, we add ".partN" at the end of the file, where N is the chunk number. String uploadedFilename = fileItem.getName() + (numChunk > 0 ? ".part" + numChunk : ""); fout = new File(ourTempDirectory + (new File(uploadedFilename)).getName()); System.out.println("[parseRequest.jsp] File Out: " + fout.toString()); // write the file fileItem.write(fout); ////////////////////////////////////////////////////////////////////////////////////// //Chunk management: if it was the last chunk, let's recover the complete file //by concatenating all chunk parts. // if (bLastChunk) { System.out.println( "[parseRequest.jsp] Last chunk received: let's rebuild the complete file (" + fileItem.getName() + ")"); //First: construct the final filename. FileInputStream fis; FileOutputStream fos = new FileOutputStream(ourTempDirectory + fileItem.getName()); int nbBytes; byte[] byteBuff = new byte[1024]; String filename; for (int i = 1; i <= numChunk; i += 1) { filename = fileItem.getName() + ".part" + i; System.out.println("[parseRequest.jsp] " + " Concatenating " + filename); fis = new FileInputStream(ourTempDirectory + filename); while ((nbBytes = fis.read(byteBuff)) >= 0) { //System.out.println("[parseRequest.jsp] " + " Nb bytes read: " + nbBytes); fos.write(byteBuff, 0, nbBytes); } fis.close(); } fos.close(); } // End of chunk management ////////////////////////////////////////////////////////////////////////////////////// fileItem.delete(); } } //while } if (generateWarning) { System.out.println("WARNING: just a warning message.\\nOn two lines!"); } System.out.println("[parseRequest.jsp] " + "Let's write a status, to finish the server response :"); //Let's wait a little, to simulate the server time to manage the file. Thread.sleep(500); //Do you want to test a successful upload, or the way the applet reacts to an error ? if (generateError) { System.out.println( "ERROR: this is a test error (forced in /wwwroot/pages/parseRequest.jsp).\\nHere is a second line!"); } else { System.out.println("SUCCESS"); PrintWriter out = ServletActionContext.getResponse().getWriter(); out.write("SUCCESS"); //System.out.println(" <span class=\"cpg_user_message\">Il y eu une erreur lors de l'excution de la requte</span>"); } System.out.println("[parseRequest.jsp] " + "End of server treatment "); } catch (Exception e) { System.out.println(""); System.out.println("ERROR: Exception e = " + e.toString()); System.out.println(""); } return SUCCESS; }