List of usage examples for org.apache.commons.fileupload FileItem getName
String getName();
From source file:ManageDatasetFiles.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from ww w . ja v a 2 s . co m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { //get the dataset files //add more files //delete some files /* TODO output your page here. You may use following sample code. */ String command = request.getParameter("command"); String datasetid = request.getParameter("datasetid"); //System.out.println("Hello World"); //System.out.println(command); //System.out.println(studyid); if (command.equalsIgnoreCase("getDatasetFiles")) { //getting dataset files //first get the filenames in the directory. //I will get the list of files in this directory and send it String datasetPath = getServletContext().getRealPath("/datasets/" + datasetid); System.out.println(datasetid); File root = new File(datasetPath); File[] list = root.listFiles(); ArrayList<String> fileItemList = new ArrayList<String>(); if (list == null) { System.out.println("List is null"); return; } for (File f : list) { if (f.isDirectory()) { ArrayList<String> dirItems = getFileItems(f.getAbsolutePath(), f.getName()); for (int i = 0; i < dirItems.size(); i++) { fileItemList.add(dirItems.get(i)); } } else { System.out.println(f.getName()); fileItemList.add(f.getName()); } } System.out.println("**** Printing the fileItems now **** "); String outputStr = ""; for (int i = 0; i < fileItemList.size(); i++) { outputStr += fileItemList.get(i); } if (outputStr.length() > 1) { out.println(outputStr); } } else if (command.equalsIgnoreCase("addDatasetFiles")) { //add the files //get the files and add them String studyFolderPath = getServletContext().getRealPath("/datasets/" + datasetid); File studyFolder = new File(studyFolderPath); //process only if its multipart content if (ServletFileUpload.isMultipartContent(request)) { try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()) .parseRequest(request); int cnt = 0; for (FileItem item : multiparts) { if (!item.isFormField()) { // cnt++; String name = new File(item.getName()).getName(); //write the file to disk if (!studyFolder.exists()) { studyFolder.mkdir(); System.out.println("The Folder has been created"); } item.write(new File(studyFolder + File.separator + name)); System.out.println("File name is :: " + name); } } System.out.print("Files successfully uploaded"); } catch (Exception ex) { //System.out.println("File Upload Failed due to " + ex); System.out.print("File Upload Failed due to " + ex); } } else { // System.out.println("The request did not include files"); System.out.println("The request did not include files"); } } else if (command.equalsIgnoreCase("deleteDatasetFiles")) { //get the array of files and delete thems String[] mpk; //get the array of file-names mpk = request.getParameterValues("fileNames"); for (int i = 0; i < mpk.length; i++) { String filePath = getServletContext().getRealPath("/datasets/" + datasetid + "/" + mpk[i]); System.out.println(filePath); File f = new File(filePath); f.delete(); } } //out.println("</html>"); } catch (Exception ex) { ex.printStackTrace(); } finally { out.close(); } }
From source file:com.krawler.spring.crm.caseModule.CrmCustomerCaseController.java
public ModelAndView uploadCustomerCaseDocs(HttpServletRequest request, HttpServletResponse response) throws ServletException { String responseMessage = ""; String caseid = ""; Map model = new HashMap(); try {/*from ww w .j a v a2s. c o m*/ if ((String) request.getSession().getAttribute(Constants.SESSION_CUSTOMER_ID) != null) { FileUploadHandler uh = new FileUploadHandler(); HashMap hm = uh.getItems(request); String companyid = sessionHandlerImpl.getCompanyid(request); String customerId = (String) request.getSession().getAttribute("customerid"); String contactId = (String) request.getSession().getAttribute("contactid"); JSONObject jobj = new JSONObject(); caseid = hm.get("caseid").toString(); KwlReturnObject kmsg = null; FileItem fileItem = (FileItem) hm.get("attachment"); String filename = fileItem.getName(); String docID = ""; if (filename != null && filename != "") { if (fileItem.getSize() <= 10485760) { //limit 10 mb kmsg = crmCustomerCaseService.uploadFile(fileItem, null, companyid, getServletContext());//Since document is uploaded by customer ,userid is null for uploadfile function Docs doc = (Docs) kmsg.getEntityList().get(0); docID = doc.getDocid(); jobj.put("docid", docID); jobj.put("companyid", companyid); jobj.put("map", "6"); jobj.put("refid", caseid); crmCustomerCaseService.saveDocumentMapping(jobj); crmCustomerCaseService.saveCustomerDocs(customerId, docID, caseid); } } request.setAttribute("casedetails", "true"); request.setAttribute("caseid", caseid); } else { request.setAttribute("logout", "true"); } } catch (Exception e) { logger.warn("Uploading Error"); e.printStackTrace(); } responseMessage = "usercases/redirect"; return new ModelAndView(responseMessage, "model", model); }
From source file:com.wfms.common.web.ConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * /*from w w w . j a va2 s . c o 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); 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); //add code filename = UUID.randomUUID().toString() + "." + extension; if (!ExtensionsHandler.isAllowed(resourceType, extension)) { ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } //add conde to validate file size else if (uplFile.getSize() > 1024 * 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:net.fckeditor.connector.ConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * /*w ww .j a va 2 s . 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. */ 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); // TODO ############???############## 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); // TODO ############??? ############ filename = UUID.randomUUID().toString() + "." + extension; if (!ExtensionsHandler.isAllowed(resourceType, extension)) { ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } else if (uplFile.getSize() >= MAX_FILESIZE) { 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:com.fujitsu.gwt.bewebapp.server.GWTUploadServlet.java
/** * Override executeAction to save the received files in a custom place and * delete this items from session.//from w w w . j a v a2s. co m */ @Override public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException { String response = ""; int cont = 0; String displayName = ""; String originalName = ""; String fileExtension = "bin"; String comments = ""; String pageId = ""; String atype = ""; String newversion = ""; String existingaid = ""; String visibility = ""; File tempFile = null; for (FileItem item : sessionFiles) { if (false == item.isFormField()) { cont++; try { String fName = item.getName(); fName = fName.replace('\\', '/'); int indx = fName.lastIndexOf("/"); if (indx > 0) { originalName = fName.substring(indx + 1); } else { originalName = fName; } int dotPos = originalName.lastIndexOf("."); if (dotPos > 0) { fileExtension = originalName.substring(dotPos + 1); } String tmpFileName = "upload-" + rd.nextInt(); // Create a temporary file placed in the default system temp // folder tempFile = File.createTempFile(tmpFileName, ".bin"); item.write(tempFile); // / Save a list with the received files receivedFiles.put(item.getFieldName(), tempFile); receivedContentTypes.put(item.getFieldName(), item.getContentType()); // / Send a customized message to the client. response += "Successfully attached the file " + item.getName(); } catch (Exception e) { throw new UploadActionException(e.getMessage()); } } else { if ("aname".equals(item.getFieldName())) { displayName = item.getString(); } else if ("desc".equals(item.getFieldName())) { comments = item.getString(); } else if ("pageid".equals(item.getFieldName())) { pageId = item.getString(); } else if ("atype".equals(item.getFieldName())) { atype = item.getString(); } else if ("newversion".equals(item.getFieldName())) { newversion = item.getString(); } else if ("existingaid".equals(item.getFieldName())) { existingaid = item.getString(); } else if ("visibility".equals(item.getFieldName())) { visibility = item.getString(); } else { System.out.println("Unknows FiledName:" + item.getFieldName() + "=" + item.getString()); } } if (displayName.length() == 0) { displayName = originalName; } else if (!displayName.endsWith("." + fileExtension)) { displayName = displayName + "." + fileExtension; } } try { String userKey = (String) request.getSession().getAttribute("userKey"); UserProfile user = null; if (userKey != null) { user = UserManager.getUserProfileByKey(userKey); } else { throw new NGException("nugen.exception.user.must.be.login", null); } AuthDummy ar = new AuthDummy(user, new StringWriter()); ar.req = request; NGPage ngp = (NGPage) NGPageIndex.getContainerByKeyOrFail(pageId); AttachmentRecord attachment = null; if (existingaid != null) { if ((!existingaid.equals("0") && (existingaid.length() > 0))) { attachment = ngp.findAttachmentByIDOrFail(existingaid); } } if (attachment == null) { //see if there exists an attachment with that name, and use that attachment = ngp.findAttachmentByName(displayName); } if (attachment == null) { //last resort, actually create one attachment = ngp.createAttachment(); attachment.setType("FILE"); } attachment.setDisplayName(displayName); attachment.setComment(comments); attachment.setModifiedBy(ar.getBestUserId()); attachment.setModifiedDate(ar.nowTime); if (atype.equals("Public")) { attachment.setVisibility(1); } else { attachment.setVisibility(2); } FileInputStream contentStream = new FileInputStream(tempFile); AttachmentVersion av = attachment.streamNewVersion(ar, ngp, contentStream); HistoryRecord.createHistoryRecord(ngp, attachment.getId(), HistoryRecord.CONTEXT_TYPE_DOCUMENT, ar.nowTime, HistoryRecord.EVENT_DOC_ADDED, ar, ""); ngp.saveContent(ar, "Modified attachments"); } catch (Exception e) { e.printStackTrace(); throw new UploadActionException(e.getMessage()); } finally { NGPageIndex.clearLocksHeldByThisThread(); } // / Remove files from session because we have a copy of them removeSessionFileItems(request); // / Send your customized message to the client. return response; }
From source file:com.hightern.fckeditor.connector.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. * /* w w w. ja v a2 s.co m*/ * @param request * the current request instance * @return the upload response instance associated with this request */ @SuppressWarnings("unchecked") UploadResponse doPost(final HttpServletRequest request) { Dispatcher.logger.debug("Entering Dispatcher#doPost"); final Context context = ThreadLocalData.getContext(); context.logBaseParameters(); UploadResponse uploadResponse = null; // check permissions for user actions if (!RequestCycleHandler.isFileUploadEnabled(request)) { uploadResponse = UploadResponse.getFileUploadDisabledError(); } 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 final ResourceType type = context.getDefaultResourceType(); final FileItemFactory factory = new DiskFileItemFactory(); final ServletFileUpload upload = new ServletFileUpload(factory); try { final List<FileItem> items = upload.parseRequest(request); // We upload just one file at the same time final FileItem uplFile = items.get(0); // Some browsers transfer the entire source path not just the // filename final String fileName = FilenameUtils.getName(uplFile.getName()); Dispatcher.logger.debug("Parameter NewFile: {}", fileName); // check the extension if (type.isDeniedExtension(FilenameUtils.getExtension(fileName))) { uploadResponse = UploadResponse.getInvalidFileTypeError(); } else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads() && !UtilsFile.isImage(uplFile.getInputStream())) { uploadResponse = UploadResponse.getInvalidFileTypeError(); } else { final String sanitizedFileName = UtilsFile.sanitizeFileName(fileName); Dispatcher.logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName); final String newFileName = connector.fileUpload(type, context.getCurrentFolderStr(), sanitizedFileName, uplFile.getInputStream()); final 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); Dispatcher.logger.debug("Parameter NewFile (renamed): {}", newFileName); } } uplFile.delete(); } catch (final InvalidCurrentFolderException e) { uploadResponse = UploadResponse.getInvalidCurrentFolderError(); } catch (final WriteException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } catch (final IOException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } catch (final FileUploadException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } } Dispatcher.logger.debug("Exiting Dispatcher#doPost"); return uploadResponse; }
From source file:hudson.jbpm.PluginImpl.java
/** * Method supporting upload from the designer at /plugin/jbpm/upload *///from w w w .j a va2s . c o m public void doUpload(StaplerRequest req, StaplerResponse rsp) throws FileUploadException, IOException, ServletException { try { ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); // Parse the request FileItem fileItem = (FileItem) upload.parseRequest(req).get(0); if (fileItem.getContentType().indexOf("application/x-zip-compressed") == -1) { throw new IOException("Not a process archive"); } log.fine("Deploying process archive " + fileItem.getName()); ZipInputStream zipInputStream = new ZipInputStream(fileItem.getInputStream()); JbpmContext jbpmContext = getCurrentJbpmContext(); log.fine("Preparing to parse process archive"); ProcessDefinition processDefinition = ProcessDefinition.parseParZipInputStream(zipInputStream); log.fine("Created a processdefinition : " + processDefinition.getName()); jbpmContext.deployProcessDefinition(processDefinition); zipInputStream.close(); rsp.forwardToPreviousPage(req); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.safetys.framework.fckeditor.connector.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 w w w.jav a 2 s . c o m*/ * @param request * the current request instance * @return the upload response instance associated with this request */ @SuppressWarnings("unchecked") UploadResponse doPost(final HttpServletRequest request) { Dispatcher.logger.debug("Entering Dispatcher#doPost"); final Context context = ThreadLocalData.getContext(); context.logBaseParameters(); UploadResponse uploadResponse = null; // check permissions for user actions if (!RequestCycleHandler.isFileUploadEnabled(request)) { uploadResponse = UploadResponse.getFileUploadDisabledError(); } 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 final ResourceType type = context.getDefaultResourceType(); final FileItemFactory factory = new DiskFileItemFactory(); final ServletFileUpload upload = new ServletFileUpload(factory); try { final List<FileItem> items = upload.parseRequest(request); // We upload just one file at the same time final FileItem uplFile = items.get(0); // Some browsers transfer the entire source path not just the // filename final String fileName = FilenameUtils.getName(uplFile.getName()); Dispatcher.logger.debug("Parameter NewFile: {}", fileName); // check the extension if (type.isDeniedExtension(FilenameUtils.getExtension(fileName))) { uploadResponse = UploadResponse.getInvalidFileTypeError(); } else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads() && !UtilsFile.isImage(uplFile.getInputStream())) { uploadResponse = UploadResponse.getInvalidFileTypeError(); } else { final String sanitizedFileName = UtilsFile.sanitizeFileName(fileName); Dispatcher.logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName); final String newFileName = this.connector.fileUpload(type, context.getCurrentFolderStr(), sanitizedFileName, uplFile.getInputStream()); final 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); Dispatcher.logger.debug("Parameter NewFile (renamed): {}", newFileName); } } uplFile.delete(); } catch (final InvalidCurrentFolderException e) { uploadResponse = UploadResponse.getInvalidCurrentFolderError(); } catch (final WriteException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } catch (final IOException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } catch (final FileUploadException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } } Dispatcher.logger.debug("Exiting Dispatcher#doPost"); return uploadResponse; }
From source file:fr.paris.lutece.plugins.genericattributes.service.upload.AbstractGenAttUploadHandler.java
/** * {@inheritDoc}//from w w w. j a v a 2 s. c om */ @Override public void addFileItemToUploadedFilesList(FileItem fileItem, String strFieldName, HttpServletRequest request) { // This is the name that will be displayed in the form. We keep // the original name, but clean it to make it cross-platform. String strFileName = UploadUtil.cleanFileName(fileItem.getName().trim()); initMap(request.getSession().getId(), buildFieldName(strFieldName)); // Check if this file has not already been uploaded List<FileItem> uploadedFiles = getListUploadedFiles(strFieldName, request.getSession()); if (uploadedFiles != null) { boolean bNew = true; if (!uploadedFiles.isEmpty()) { Iterator<FileItem> iterUploadedFiles = uploadedFiles.iterator(); while (bNew && iterUploadedFiles.hasNext()) { FileItem uploadedFile = iterUploadedFiles.next(); String strUploadedFileName = UploadUtil.cleanFileName(uploadedFile.getName().trim()); // If we find a file with the same name and the same // length, we consider that the current file has // already been uploaded bNew = !(StringUtils.equals(strUploadedFileName, strFileName) && (uploadedFile.getSize() == fileItem.getSize())); } } if (bNew) { uploadedFiles.add(fileItem); } } }
From source file:cn.edu.hbcit.servlets.ConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * // w w w . ja va2s .com * 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"); }