List of usage examples for org.apache.commons.fileupload FileItem getInputStream
InputStream getInputStream() throws IOException;
From source file:csiro.pidsvc.mappingstore.Manager.java
@SuppressWarnings("unchecked") protected String unwrapCompressedBackupFile(HttpServletRequest request, ICallback callback) { java.util.List<FileItem> fileList = null; GZIPInputStream gis = null;/* www . j av a 2 s . c o m*/ String ret = null; try { DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); // Set the size threshold, above which content will be stored on disk. fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB // fileItemFactory.setSizeThreshold(100 * 1024); // 100 KB // Set the temporary directory to store the uploaded files of size above threshold. fileItemFactory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); fileList = uploadHandler.parseRequest(request); for (FileItem item : fileList) { if (item.isFormField()) continue; try { // Try to restore the backup file as it was in binary format. gis = new GZIPInputStream(item.getInputStream()); ret = callback.process(gis); gis.close(); } catch (IOException ex) { String msg = ex.getMessage(); if (msg != null && msg.equalsIgnoreCase("Not in GZIP format")) { // Try to restore the backup file as it was unzipped. ret = callback.process(item.getInputStream()); } else throw ex; } // Process the first uploaded file only. return ret; } } catch (Exception ex) { String msg = ex.getMessage(); Throwable linkedException = ex.getCause(); _logger.warn(msg); if (linkedException != null) _logger.warn(linkedException.getMessage()); if (msg != null && msg.equalsIgnoreCase("Not in GZIP format")) return "ERROR: Unknown file format."; else return "ERROR: " + (msg == null ? "Something went wrong." : msg + (linkedException == null ? "" : " " + linkedException.getMessage())); } finally { try { // Close the stream. gis.close(); } catch (Exception ex) { } if (fileList != null) { // Delete all uploaded files. for (FileItem item : fileList) { if (!item.isFormField() && !item.isInMemory()) ((DiskFileItem) item).delete(); } } } _logger.trace("No file found."); return "ERROR: No file."; }
From source file:com.bigdata.rdf.sail.webapp.UpdateServlet.java
private boolean validateItem(final HttpServletResponse resp, final FileItem item) throws IOException { final String contentType = item.getContentType(); if (contentType == null) { buildAndCommitResponse(resp, HTTP_BADREQUEST, MIME_TEXT_PLAIN, "Content-Type not specified"); return false; }// ww w . ja v a 2 s . c o m final RDFFormat format = RDFFormat.forMIMEType(new MiniMime(contentType).getMimeType()); if (format == null) { buildAndCommitResponse(resp, HTTP_BADREQUEST, MIME_TEXT_PLAIN, "Content-Type not recognized as RDF: " + contentType); return false; } final RDFParserFactory rdfParserFactory = RDFParserRegistry.getInstance().get(format); if (rdfParserFactory == null) { buildAndCommitResponse(resp, HTTP_INTERNALERROR, MIME_TEXT_PLAIN, "Parser factory not found: Content-Type=" + contentType + ", format=" + format); return false; } if (item.getInputStream() == null) { buildAndCommitResponse(resp, HTTP_BADREQUEST, MIME_TEXT_PLAIN, "No content"); return false; } return true; }
From source file:mml.handler.post.MMLPostHandler.java
/** * Parse the import params from the request * @param request the http request//from ww w. j a va 2 s. c o m */ void parseImportParams(HttpServletRequest request) throws MMLException { try { FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List items = upload.parseRequest(request); for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); if (item.isFormField()) { String fieldName = item.getFieldName(); if (fieldName != null) { String contents = item.getString(this.encoding); if (fieldName.equals(Params.DOCID)) { int index = contents.lastIndexOf("."); if (index != -1) contents = contents.substring(0, index); docid = contents; } else if (fieldName.equals(Params.AUTHOR)) this.author = contents; else if (fieldName.equals(Params.TITLE)) this.title = contents; else if (fieldName.equals(Params.STYLE)) this.style = contents; else if (fieldName.equals(Params.FORMAT)) this.format = contents; else if (fieldName.equals(Params.SECTION)) this.section = contents; else if (fieldName.equals(Params.VERSION1)) this.version1 = contents; else if (fieldName.equals(Params.ENCODING)) encoding = contents; else if (fieldName.equals(Params.ANNOTATIONS)) annotations = (JSONArray) JSONValue.parse(contents); } } else if (item.getName().length() > 0) { try { // item.getName retrieves the ORIGINAL file name String type = item.getContentType(); if (type != null) { if (type.startsWith("image/")) { InputStream is = item.getInputStream(); ByteHolder bh = new ByteHolder(); while (is.available() > 0) { byte[] b = new byte[is.available()]; is.read(b); bh.append(b); } ImageFile iFile = new ImageFile(item.getName(), item.getContentType(), bh.getData()); if (images == null) images = new ArrayList<ImageFile>(); images.add(iFile); } else if (type.equals("text/plain")) { InputStream is = item.getInputStream(); ByteHolder bh = new ByteHolder(); while (is.available() > 0) { byte[] b = new byte[is.available()]; is.read(b); bh.append(b); } String style = new String(bh.getData(), encoding); if (files == null) files = new ArrayList<String>(); files.add(style); } } } catch (Exception e) { throw new MMLException(e); } } } } catch (Exception e) { throw new MMLException(e); } }
From source file:com.stratelia.webactiv.survey.control.SurveySessionController.java
public void saveSynthesisFile(FileItem fileSynthesis) throws SurveyException { SilverTrace.info("Survey", "SurveySessionController.saveSynthesisFile", "Survey.MSG_ENTRY_METHOD"); QuestionContainerDetail survey = this.getSessionSurvey(); try {//w w w. j a v a 2s . c o m Date creationDate = new Date(); String filename = fileSynthesis.getName(); SimpleAttachment file = new SimpleAttachment(FileUtil.getFilename(filename), I18NHelper.defaultLanguage, filename, "", fileSynthesis.getSize(), FileUtil.getMimeType(filename), this.getUserId(), creationDate, null); SimpleDocument document = new SimpleDocument( new SimpleDocumentPK(null, survey.getComponentInstanceId()), survey.getId(), 0, false, file); AttachmentServiceFactory.getAttachmentService().createAttachment(document, fileSynthesis.getInputStream(), true); } catch (IOException e) { throw new SurveyException("SurveySessionController.saveSynthesisFile", SurveyException.WARNING, "Survey.EX_PROBLEM_TO_UPDATE_SURVEY", "id = " + survey.getId(), e); } }
From source file:com.silverpeas.classifieds.control.ClassifiedsSessionController.java
/** * update classified image /*from w w w . j a v a 2s . c o m*/ * @param fileImage : FileItem * @param imageId : String * @param classifiedId : String */ public void updateClassifiedImage(FileItem fileImage, String imageId, String classifiedId) { SimpleDocument classifiedImage = null; try { SimpleDocumentPK sdPK = new SimpleDocumentPK(imageId, getComponentId()); classifiedImage = AttachmentServiceFactory.getAttachmentService().searchDocumentById(sdPK, null); } catch (Exception e) { throw new ClassifiedsRuntimeException("ClassifiedsSessionController.updateClassifiedImage()", SilverpeasRuntimeException.ERROR, "classifieds.MSG_ERR_GET_IMAGE", e); } if (classifiedImage != null) { Date updateDate = new Date(); String fileName = FileUtil.getFilename(fileImage.getName()); long size = fileImage.getSize(); String mimeType = FileUtil.getMimeType(fileName); classifiedImage.setDocumentType(DocumentType.attachment); classifiedImage.setFilename(fileName); classifiedImage.setLanguage(null); classifiedImage.setTitle(""); classifiedImage.setDescription(""); classifiedImage.setSize(size); classifiedImage.setContentType(mimeType); classifiedImage.setUpdatedBy(getUserId()); classifiedImage.setUpdated(updateDate); try { AttachmentServiceFactory.getAttachmentService().updateAttachment(classifiedImage, fileImage.getInputStream(), true, false); } catch (Exception e) { throw new ClassifiedsRuntimeException("ClassifiedsSessionController.updateClassifiedImage()", SilverpeasRuntimeException.ERROR, "classifieds.MSG_CLASSIFIED_IMAGE_NOT_UPDATE", e); } } else { createClassifiedImage(fileImage, classifiedId); } }
From source file:com.openkm.servlet.admin.StampServlet.java
@SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("doPost({}, {})", request, response); request.setCharacterEncoding("UTF-8"); String action = WebUtils.getString(request, "action"); Session session = null;//from w w w .j a v a 2 s . c o m updateSessionManager(request); try { if (ServletFileUpload.isMultipartContent(request)) { session = JCRUtils.getSession(); InputStream is = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); StampImage si = new StampImage(); for (Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem item = it.next(); if (item.isFormField()) { if (item.getFieldName().equals("action")) { action = item.getString("UTF-8"); } else if (item.getFieldName().equals("si_id")) { si.setId(Integer.parseInt(item.getString("UTF-8"))); } else if (item.getFieldName().equals("si_name")) { si.setName(item.getString("UTF-8")); } else if (item.getFieldName().equals("si_description")) { si.setDescription(item.getString("UTF-8")); } else if (item.getFieldName().equals("si_layer")) { si.setLayer(Integer.parseInt(item.getString("UTF-8"))); } else if (item.getFieldName().equals("si_opacity")) { si.setOpacity(Float.parseFloat(item.getString("UTF-8"))); } else if (item.getFieldName().equals("si_expr_x")) { si.setExprX(item.getString("UTF-8")); } else if (item.getFieldName().equals("si_expr_y")) { si.setExprY(item.getString("UTF-8")); } else if (item.getFieldName().equals("si_active")) { si.setActive(true); } else if (item.getFieldName().equals("si_users")) { si.getUsers().add(item.getString("UTF-8")); } } else { is = item.getInputStream(); si.setImageMime(Config.mimeTypes.getContentType(item.getName())); si.setImageContent(SecureStore.b64Encode(IOUtils.toByteArray(is))); is.close(); } } if (action.equals("imageCreate")) { int id = StampImageDAO.create(si); // Activity log UserActivity.log(session.getUserID(), "ADMIN_STAMP_IMAGE_CREATE", Integer.toString(id), si.toString()); imageList(session, request, response); } else if (action.equals("imageEdit")) { StampImageDAO.update(si); // Activity log UserActivity.log(session.getUserID(), "ADMIN_STAMP_IMAGE_EDIT", Integer.toString(si.getId()), si.toString()); imageList(session, request, response); } else if (action.equals("imageDelete")) { StampImageDAO.delete(si.getId()); // Activity log UserActivity.log(session.getUserID(), "ADMIN_STAMP_IMAGE_DELETE", Integer.toString(si.getId()), null); imageList(session, request, response); } } } catch (LoginException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (RepositoryException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (DatabaseException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (FileUploadException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } finally { JCRUtils.logout(session); } }
From source file:com.bigdata.rockstor.console.UploadServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (!ServletFileUpload.isMultipartContent(req)) { LOG.error("It is not a MultipartContent, return error."); resp.sendError(500, "It is not a MultipartContent, return error."); return;//from ww w .j a v a 2 s.c om } FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(1024 * 1024 * 512); List<FileItem> fileItems = null; try { fileItems = upload.parseRequest(req); LOG.info("parse requeset success : items num : " + fileItems.size()); } catch (FileUploadException e) { LOG.error("parse requeset failed !"); resp.sendError(500, "parse requeset failed !"); return; } HashMap<String, String> headMap = new HashMap<String, String>(); FileItem theFile = null; long size = -1; URI uri = null; Iterator<FileItem> iter = fileItems.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = null; try { value = item.getString("UTF-8").trim(); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } LOG.info("Parse head info : " + name + " -- " + value); if (name.equals("ObjName")) { try { uri = new URI(value); } catch (URISyntaxException e) { LOG.info("Parse uri info error : " + value); uri = null; } } else if (name.equals("ObjSize")) { try { size = Long.parseLong(value); } catch (Exception e) { LOG.error("Parse objSize error : " + value); } } else { headMap.put(name, value); } } else { theFile = item; } } if (size == -1 || uri == null || theFile == null || headMap.size() == 0) { LOG.error("Parse upload info error : size==-1 || uri == null || theFile == null || headMap.size()==0"); resp.sendError(500, "Parse upload info error : size==-1 || uri == null || theFile == null || headMap.size()==0"); return; } HttpPut put = new HttpPut(); put.setURI(uri); for (Map.Entry<String, String> e : headMap.entrySet()) { if ("Filename".equals(e.getKey())) continue; put.setHeader(e.getKey(), e.getValue()); } put.setEntity(new InputStreamEntity(theFile.getInputStream(), size)); DefaultHttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(put); if (200 != response.getStatusLine().getStatusCode()) { LOG.error("Put object error : " + response.getStatusLine().getStatusCode() + " : " + response.getStatusLine().getReasonPhrase()); resp.sendError(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); return; } LOG.info("Put object OK : " + uri); response.setStatusCode(200); }
From source file:com.weaforce.system.component.fckeditor.connector.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"); // "FileUpload" String typeStr = request.getParameter("Type"); // Image String currentFolderStr = request.getParameter("CurrentFolder"); // "/" imageSubPath = request.getParameter("subpath"); logger.info("Parameter Command in doPost: {}", commandStr); logger.info("Parameter Type in doPost: {}", typeStr); logger.info("Parameter CurrentFolder in doPost: {}", currentFolderStr); UploadResponse ur; // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr' // are empty if (StringUtil.isEmpty(commandStr) && StringUtil.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 (!FileUtils.isValidPath(currentFolderStr)) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr); //String userLogin = Security.getCurrentUserName().toLowerCase(); // typePath=\\data\\file in the weaforce.properties String typePath = UtilsFile.constructServerSidePath(request, resourceType); typePath = typePath + "/" + imageSubPath + "/" + DateUtil.getCurrentYearObliqueMonthStr(); System.out.println("typePath: " + typePath); logger.info("doPost: typePath value is: {}", typePath); String typeDirPath = typePath; FileUtils.checkAndCreateDir(typeDirPath); File typeDir = new File(typeDirPath); 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); if (!ExtensionsHandler.isAllowed(resourceType, extension)) ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); else { filename = getFilename(typeDirPath, System.currentTimeMillis(), extension); File pathToSave = new File(currentDir, filename); // String responseUrl = UtilsResponse // .constructResponseUrl(request, resourceType, // currentFolderStr, true, // ConnectorHandler.isFullUrl()); String responseUrl = UtilsResponse.constructResponseUrl(resourceType, imageSubPath, currentFolderStr); if (StringUtil.isEmpty(newFilename)) { responseUrl = responseUrl + DateUtil.getCurrentYearObliqueMonthStr() + "/"; ur = new UploadResponse(UploadResponse.SC_OK, responseUrl.concat(filename)); } else ur = new UploadResponse(UploadResponse.SC_RENAMED, responseUrl.concat(newFilename), newFilename); // secure image check if (resourceType.equals(ResourceTypeHandler.IMAGE) && ConnectorHandler.isSecureImageUploads()) { if (FileUtils.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); } // System.out.println("newFilename2: " + newFilename); } } out.print(ur); out.flush(); out.close(); logger.debug("Exiting Connector#doPost"); }
From source file:com.sketchy.server.ImageUploadServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JSONServletResult jsonServletResult = new JSONServletResult(Status.SUCCESS); try {//from w w w. java2 s. c o m boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(FileUtils.getTempDirectory()); factory.setSizeThreshold(MAX_SIZE); ServletFileUpload servletFileUpload = new ServletFileUpload(factory); List<FileItem> files = servletFileUpload.parseRequest(request); for (FileItem fileItem : files) { String uploadFileName = fileItem.getName(); if (StringUtils.isNotBlank(uploadFileName)) { // Don't allow \\ in the filename, assume it's a directory separator and convert to "/" // and take the filename after the last "/" // This will fix the issue of Jetty not reading and serving files // with "\" (%5C) characters // This also fixes the issue of IE sometimes sending the whole path // (depending on the security settings) uploadFileName = StringUtils.replaceChars(uploadFileName, "\\", "/"); if (StringUtils.contains(uploadFileName, "/")) { uploadFileName = StringUtils.substringAfterLast(uploadFileName, "/"); } File uploadFile = HttpServer.getUploadFile(uploadFileName); // make sure filename is actually in the upload directory // we don't want any funny games if (!uploadFile.getParentFile().equals(HttpServer.IMAGE_UPLOAD_DIRECTORY)) { throw new RuntimeException("Can not upload File. Invalid directory!"); } // if saved ok, then need to add the data file SourceImageAttributes sourceImageAttributes = new SourceImageAttributes(); sourceImageAttributes.setImageName(uploadFileName); File pngFile = HttpServer.getUploadFile(sourceImageAttributes.getImageFilename()); if (pngFile.exists()) { throw new Exception( "Can not Upload file. File '" + uploadFileName + "' already exists!"); } File dataFile = HttpServer.getUploadFile(sourceImageAttributes.getDataFilename()); // Convert the image to a .PNG file BufferedImage image = ImageUtils.loadImage(fileItem.getInputStream()); ImageUtils.saveImage(pngFile, image); sourceImageAttributes.setWidth(image.getWidth()); sourceImageAttributes.setHeight(image.getHeight()); FileUtils.writeStringToFile(dataFile, sourceImageAttributes.toJson()); jsonServletResult.put("imageName", uploadFileName); } } } } catch (Exception e) { jsonServletResult = new JSONServletResult(Status.ERROR, e.getMessage()); } response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().print(jsonServletResult.toJSONString()); }
From source file:com.yeoou.fckeditor.ConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * //from w w w .java2 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 { upload.setHeaderEncoding("UTF-8"); 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 { // 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"); }