List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload setHeaderEncoding
public void setHeaderEncoding(String encoding)
From source file:com.github.cxt.Myjersey.jerseycore.FileResource.java
@Path("upload2") @POST//w w w .j a va2 s .c om @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_JSON) public String uploadFile(@Context HttpServletRequest request) throws IOException { //??,httpclent? System.out.println(request.getCharacterEncoding()); ServletFileUpload upload = new ServletFileUpload(); upload.setHeaderEncoding(CHARSET); try { FileItemIterator fileIterator = upload.getItemIterator(request); while (fileIterator.hasNext()) { FileItemStream item = fileIterator.next(); InputStream is = item.openStream(); try { if (!item.isFormField()) { String fileName = item.getName(); if (fileName == null || fileName.trim().equals("")) { continue; } String name = Calendar.getInstance().getTimeInMillis() + fileName; String path = request.getServletContext().getRealPath("/"); path += File.separator + "data" + File.separator + name; File file = new File(path); FileUtils.copyInputStreamToFile(is, file); } else { System.out.println(Streams.asString(is, CHARSET)); } } finally { if (null != is) { try { is.close(); } catch (IOException ignore) { } } } } return "{\"success\": true}"; } catch (IOException | FileUploadException e) { return "{\"success\": false}"; } }
From source file:com.pureinfo.tgirls.servlet.TestServlet.java
private File uploadFile(HttpServletRequest request) throws Exception { // ,??ServletFileUpload DiskFileItemFactory dfif = new DiskFileItemFactory(); dfif.setSizeThreshold(4096);// ?,4K. String tempfilepath = FileFactory.getInstance().lookupPathConfigByFlag("UP", true).getLocalPath(); dfif.setRepository(new File(tempfilepath));// // //w w w. j a v a2 s.c o m ServletFileUpload sfu = new ServletFileUpload(dfif); sfu.setHeaderEncoding("utf-8"); // //sfu.setSizeMax(MAX_SIZE_5M); // PrintWriter out = response.getWriter(); // request List fileList = null; try { fileList = sfu.parseRequest(request); } catch (FileUploadException e) {// ? logger.error("FileUploadException", e); if (e instanceof SizeLimitExceededException) { throw new Exception("?:" + MAX_SIZE_5M / 1024 + "K"); } } // if (fileList == null || fileList.size() == 0) { throw new Exception(""); } // Iterator fileItr = fileList.iterator(); // ? while (fileItr.hasNext()) { FileItem fileItem = null; String path = null; long size = 0; // ? fileItem = (FileItem) fileItr.next(); // ?form?(<input type="text" />) if (fileItem == null || fileItem.isFormField()) { continue; } // path = fileItem.getName(); logger.debug("path:" + path); // ? size = fileItem.getSize(); if ("".equals(path) || size == 0) { throw new Exception(""); } // ?? String t_name = path.substring(path.lastIndexOf("\\") + 1); // ??(????) String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1); logger.debug("the file ext name:" + t_ext); // ??? int allowFlag = 0; int allowedExtCount = allowedExt.length; for (; allowFlag < allowedExtCount; allowFlag++) { if (allowedExt[allowFlag].equals(t_ext.toLowerCase())) break; } if (allowFlag == allowedExtCount) { String error = ":"; for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++) error += "*." + allowedExt[allowFlag] + " "; throw new Exception(error); } // ? String u_name = FileFactory.getInstance().getNextFileName("UP", t_ext, true); File temp = new File(u_name); int[] imgSize = getimgSize(fileItem); if ((imgSize[0] > 0 && imgSize[0] < 300) || (imgSize[1] > 0 && imgSize[1] < 300)) { throw new Exception("300x300"); } logger.debug("to write file:" + temp); // ? fileItem.write(temp); temp = resizePic(temp); return temp; } throw new Exception(""); }
From source file:com.niconico.mylasta.direction.sponsor.NiconicoMultipartRequestHandler.java
protected ServletFileUpload createServletFileUpload(HttpServletRequest request) { final DiskFileItemFactory fileItemFactory = createDiskFileItemFactory(); final ServletFileUpload upload = newServletFileUpload(fileItemFactory); upload.setHeaderEncoding(request.getCharacterEncoding()); upload.setSizeMax(getSizeMax());//from w ww.j a v a2s .com return upload; }
From source file:com.twosigma.beaker.core.module.elfinder.ConnectorController.java
private HttpServletRequest parseMultipartContent(final HttpServletRequest request) throws Exception { if (!ServletFileUpload.isMultipartContent(request)) return request; final Map<String, String> requestParams = new HashMap<String, String>(); List<FileItemStream> listFiles = new ArrayList<FileItemStream>(); // Parse the request ServletFileUpload sfu = new ServletFileUpload(); String characterEncoding = request.getCharacterEncoding(); if (characterEncoding == null) { characterEncoding = "UTF-8"; }/*from w ww . ja v a 2 s. c om*/ sfu.setHeaderEncoding(characterEncoding); FileItemIterator iter = sfu.getItemIterator(request); while (iter.hasNext()) { final FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { requestParams.put(name, Streams.asString(stream, characterEncoding)); } else { String fileName = item.getName(); if (fileName != null && !"".equals(fileName.trim())) { ByteArrayOutputStream os = new ByteArrayOutputStream(); IOUtils.copy(stream, os); final byte[] bs = os.toByteArray(); stream.close(); listFiles.add((FileItemStream) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] { FileItemStream.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("openStream".equals(method.getName())) { return new ByteArrayInputStream(bs); } return method.invoke(item, args); } })); } } } request.setAttribute(FileItemStream.class.getName(), listFiles); Object proxyInstance = Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] { HttpServletRequest.class }, new InvocationHandler() { @Override public Object invoke(Object arg0, Method arg1, Object[] arg2) throws Throwable { // we replace getParameter() and getParameterValues() // methods if ("getParameter".equals(arg1.getName())) { String paramName = (String) arg2[0]; return requestParams.get(paramName); } if ("getParameterValues".equals(arg1.getName())) { String paramName = (String) arg2[0]; // normalize name 'key[]' to 'key' if (paramName.endsWith("[]")) paramName = paramName.substring(0, paramName.length() - 2); if (requestParams.containsKey(paramName)) return new String[] { requestParams.get(paramName) }; // if contains key[1], key[2]... int i = 0; List<String> paramValues = new ArrayList<String>(); while (true) { String name2 = String.format("%s[%d]", paramName, i++); if (requestParams.containsKey(name2)) { paramValues.add(requestParams.get(name2)); } else { break; } } return paramValues.isEmpty() ? new String[0] : paramValues.toArray(new String[paramValues.size()]); } return arg1.invoke(request, arg2); } }); return (HttpServletRequest) proxyInstance; }
From source file:com.github.thorqin.webapi.FileManager.java
public List<FileInfo> saveUploadFiles(HttpServletRequest request, int maxSize) throws ServletException, IOException, FileUploadException { List<FileInfo> uploadList = new LinkedList<>(); request.setCharacterEncoding("utf-8"); ServletFileUpload upload = new ServletFileUpload(); upload.setHeaderEncoding("UTF-8"); if (!ServletFileUpload.isMultipartContent(request)) { return uploadList; }/*w ww . ja v a2 s .co m*/ upload.setSizeMax(maxSize); FileItemIterator iter; iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); try (InputStream stream = item.openStream()) { if (!item.isFormField()) { FileInfo info = new FileInfo(); info.setFileName(item.getName()); if (getFileMIME(info.getExtName()) == null) { logger.log(Level.WARNING, "Upload file's MIME type isn't permitted."); continue; } info = store(stream, info.fileName); uploadList.add(info); } } } return uploadList; }
From source file:kg12.Ex12_1.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w . j a va 2 s . c om * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet Ex12_1</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>???</h1>"); // multipart/form-data ?? if (ServletFileUpload.isMultipartContent(request)) { out.println("???<br>"); } else { out.println("?????<br>"); out.close(); return; } // ServletFileUpload?? DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload sfu = new ServletFileUpload(factory); // ??? int fileSizeMax = 1024000; factory.setSizeThreshold(1024); sfu.setSizeMax(fileSizeMax); sfu.setHeaderEncoding("UTF-8"); // ? String format = "%s:%s<br>%n"; // ??????? FileItemIterator fileIt = sfu.getItemIterator(request); while (fileIt.hasNext()) { FileItemStream item = fileIt.next(); if (item.isFormField()) { // out.print("<br>??<br>"); out.printf(format, "??", item.getFieldName()); InputStream is = item.openStream(); // ? byte ?? byte[] b = new byte[255]; // byte? b ???? is.read(b, 0, b.length); // byte? b ? "UTF-8" ??String??? result ? String result = new String(b, "UTF-8"); out.printf(format, "", result); } else { // out.print("<br>??<br>"); out.printf(format, "??", item.getName()); } } out.println("</body>"); out.println("</html>"); } catch (FileUploadException e) { out.println(e + "<br>"); throw new ServletException(e); } catch (Exception e) { out.println(e + "<br>"); throw new ServletException(e); } finally { out.close(); } }
From source file:net.i2cat.csade.life2.backoffice.servlet.UserManagementService.java
/** * Funcin que se ejecuta cuando el servlet recibe los datos *///from w ww .j a v a 2 s. co m protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ChangablePropertiesManager cpm = new ChangablePropertiesManager(this.getServletContext()); String operation = request.getParameter("operation"); PlatformUserManager pum = new PlatformUserManager(); String data = ""; if (operation != null && !"".equals(operation)) { if (operation.equals("savePicturePreference")) { String photo_hor = request.getParameter("photo_hor"); cpm.saveProperty("photo_hor", photo_hor); data = "{ \"message\": \"preferences saved.\" }"; } if (operation.equals("getPicturePreference")) { String photo_hor = cpm.getProperty("photo_hor"); data = "{ \"photo_hor\": \"" + photo_hor + "\"}"; } if (operation.equals("getPlatformUser")) { String login = request.getParameter("login"); try { data = pum.getUser(login).toJSON().toString(); } catch (RemoteException re) { data = "{ \"message\": \"Could not not retrieve user with login=" + login + " Reason:" + re.getMessage() + ".\" }"; } catch (ServiceException se) { data = "{ \"message\": \"Could not not retrieve user with login=" + login + " Reason:" + se.getMessage() + ".\" }"; } } if (operation.equals("delPlatformUser")) { String login = request.getParameter("login"); try { if (!request.isUserInRole("admin")) throw new ServiceException("You are not allowed to delete users"); if (login != null && login.equals(request.getUserPrincipal().getName())) throw new ServiceException("You cannot delete your own user"); pum.deleteUser(login); data = "{ \"message\": \"User with login " + login + " deleted.\" }"; } catch (RemoteException re) { data = "{ \"message\": \"Could not not delete user with login=" + login + " Reason:" + re.getMessage() + ".\" }"; } catch (ServiceException se) { data = "{ \"message\": \"Could not not delete user with login=" + login + " Reason:" + se.getMessage() + ".\" }"; } } if (operation.equals("savePlatformUser")) { FileItem uploadedFile = null; PlatformUser user = null; int res = 0; byte[] foto = null; try { if (!request.isUserInRole("admin")) throw new ServiceException("You are not allowed to upadte users"); user = new PlatformUser(); user.setNew(false); ServletFileUpload sfu = new ServletFileUpload(new DiskFileItemFactory()); sfu.setFileSizeMax(329000); sfu.setHeaderEncoding("UTF-8"); @SuppressWarnings("unchecked") List<FileItem> items = sfu.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { if (item.getFieldName().equals("login")) user.setLogin(item.getString()); if (item.getFieldName().equals("username")) user.setLogin(item.getString()); if (item.getFieldName().equals("password")) { user.setPass(item.getString()); } if (item.getFieldName().equals("idUser")) { if (item.getString() == null || "".equals(item.getString())) user.setNew(true); } if (item.getFieldName().equals("name")) { byte[] fnb = item.get(); String text = PasswordGenerator.utf8Decoder(fnb); user.setName(text); } if (item.getFieldName().equals("email")) { String mail = item.getString(); if (MailUtils.isValidEmail(mail)) user.setEmail(mail); else throw new ServiceException("El email del usuario es incorrecto"); } if (item.getFieldName().equals("telephonenumber")) user.setTelephonenumber(item.getString()); if (item.getFieldName().equals("role")) user.setRole(Integer.parseInt(item.getString())); if (item.getFieldName().equals("language")) user.setLanguage(item.getString()); if (item.getFieldName().equals("notification_level")) user.setNotification_level(item.getString()); if (item.getFieldName().equals("promoter_id")) user.setPromoter_id(item.getString()); if (item.getFieldName().equals("user_average_mark")) user.setUser_average_mark(item.getString()); if (item.getFieldName().equals("user_votes")) user.setUser_votes(item.getString()); if (item.getFieldName().equals("latitude")) user.setHome_area_lat(item.getString()); if (item.getFieldName().equals("longitude")) user.setHome_area_lon(item.getString()); if (item.getFieldName().equals("enabled")) user.setEnabled(item.getString().equals("0") ? 0 : 1); } else { uploadedFile = item; String inputExtension = FilenameUtils .getExtension(uploadedFile.getName().toLowerCase()); if ("jpg".equals(inputExtension) || "gif".equals(inputExtension) || "png".equals(inputExtension)) { InputStream filecontent = item.getInputStream(); foto = new byte[(int) uploadedFile.getSize()]; filecontent.read(foto, 0, (int) uploadedFile.getSize()); } //else // throw new FileUploadException("Extension not supported. Only jpg,gif or png files are allowed"); } } res = pum.saveUser(user); if (foto != null) { //String v=cpm.getProperty("photo_hor"); //byte[] resizedPhoto=ImageUtil.resizeImageAsJPG(foto, (v==null || "".equals(v)) ?200:Integer.parseInt(v)); pum.uploadFoto(user.getLogin(), foto); } data = "{ \"message\": \"User with login " + user.getLogin() + " (id=" + res + ") saved.\" }"; } catch (RemoteException exc) { data = "{ \"message\": \"Could not not save user with login=" + user.getLogin() + " Reason:" + exc.getMessage() + ".\" }"; } catch (ServiceException exc) { data = "{ \"message\": \"Could not not save user with login=" + user.getLogin() + " Reason:" + exc.getMessage() + ".\" }"; } catch (FileUploadException exc) { data = "{ \"message\": \"User with login " + user.getLogin() + " (id=" + res + ") saved, but there was a problem uploading picture:" + exc.getMessage() + "\" }"; } } if (operation.equals("listPlatformUsers")) { JQueryDataTableParamModel param = DataTablesParamUtility.getParam(request); try { JSONObject jsonResponse = pum.getPlatformUsersJSON(param); data = jsonResponse.toString(); } catch (RemoteException re) { data = "{ \"message\": \"Could not not retrieve platform user listing. Reason:" + re.getMessage() + ".\" }"; } catch (ServiceException se) { data = "{ \"message\": \"Could not not retrieve platform user listing. Reason:" + se.getMessage() + ".\" }"; } } } response.setContentType("application/json;charset=UTF-8"); //response.setContentType("application/json"); response.getWriter().print(data); response.getWriter().close(); }
From source file:com.wellmail.servlet.ConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * /*from w ww . j a v a 2 s . 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); 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); //20k else if (uplFile.getSize() > 100 * 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:jp.co.opentone.bsol.linkbinder.view.filter.UploadFileFilter.java
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { // ????//from w ww. j a v a 2 s. c o m if (!(req instanceof HttpServletRequest)) { chain.doFilter(req, res); return; } HttpServletRequest httpReq = (HttpServletRequest) req; // ?????????? if (!ServletFileUpload.isMultipartContent(httpReq)) { chain.doFilter(req, res); return; } DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload sfu = new ServletFileUpload(factory); factory.setSizeThreshold(thresholdSize); sfu.setSizeMax(maxSize); // sfu.setHeaderEncoding(req.getCharacterEncoding()); try { @SuppressWarnings("unchecked") Iterator<FileItem> ite = sfu.parseRequest(httpReq).iterator(); List<String> keys = new ArrayList<String>(); List<String> names = new ArrayList<String>(); List<String> fieldNames = new ArrayList<String>(); List<Long> fileSize = new ArrayList<Long>(); while (ite.hasNext()) { String name = null; FileItem item = ite.next(); // ???? if (!(item.isFormField())) { name = item.getName(); name = name.substring(name.lastIndexOf('\\') + 1); if (StringUtils.isEmpty(name)) { continue; } File f = null; // CHECKSTYLE:OFF // ??????????. while ((f = new File(createTempFilePath())).exists()) { } // CHECKSTYLE:ON if (!validateByteLength(name, maxFilenameLength, minFilenameLength)) { // ???? names.add(name); keys.add(UploadedFile.KEY_FILENAME_OVER); fieldNames.add(item.getFieldName()); fileSize.add(item.getSize()); } else if (item.getSize() == 0) { // 0 names.add(name); keys.add(UploadedFile.KEY_SIZE_ZERO); fieldNames.add(item.getFieldName()); fileSize.add(item.getSize()); } else if (maxFileSize > 0 && item.getSize() > maxFileSize) { // ? // ?0??????Validation names.add(name); keys.add(UploadedFile.KEY_SIZE_OVER); fieldNames.add(item.getFieldName()); fileSize.add(item.getSize()); } else { item.write(f); names.add(name); keys.add(f.getName()); fieldNames.add(item.getFieldName()); fileSize.add(item.getSize()); } f.deleteOnExit(); } } // UploadFileFilterResult result = new UploadFileFilterResult(); result.setResult(UploadFileFilterResult.RESULT_OK); result.setNames(names.toArray(new String[names.size()])); result.setKeys(keys.toArray(new String[keys.size()])); result.setFieldNames(fieldNames.toArray(new String[fieldNames.size()])); result.setFileSize(fileSize.toArray(new Long[fileSize.size()])); writeResponse(req, res, result); } catch (Exception e) { e.printStackTrace(); // UploadFileFilterResult result = new UploadFileFilterResult(); result.setResult(UploadFileFilterResult.RESULT_NG); writeResponse(req, res, result); } }
From source file:com.yeoou.fckeditor.ConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * //from w ww. j a va 2 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"); }