List of usage examples for org.apache.commons.fileupload FileItem delete
void delete();
From source file:com.windy.zfxy.fck.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. * // www . jav a 2s. c om * @param request * the current request instance * @return the upload response instance associated with this request */ @SuppressWarnings("unchecked") 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()); fileName = java.util.UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(fileName); logger.debug("Parameter NewFile: {}", 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); // this.setPhotoPath(fileUrl); 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.zhoujian.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. * // w ww . j av a 2 s. 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); upload.setHeaderEncoding("utf-8"); 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); // 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); } } // if (uplFile.getSize() > 1024 * 500) { uploadResponse = new UploadResponse(204); } 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.wwl.utils.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 . j a v a2 s .co m * @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.isEnabledForFileUpload(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); upload.setHeaderEncoding("utf-8"); 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); // check the extension if (type.isNotAllowedExtension(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 { //fileName = UUID.randomUUID().toString()+"."+FilenameUtils.getExtension(fileName); fileName = new Date().getTime() + "." + FilenameUtils.getExtension(fileName); 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.silverpeas.servlets.upload.AjaxFileUploadServlet.java
/** * Do the effective upload of files./*w ww .j a v a2s. c om*/ * * @param session the HttpSession * @param request the multpart request * @throws IOException */ @SuppressWarnings("unchecked") private void doFileUpload(HttpSession session, HttpServletRequest request) throws IOException { try { session.setAttribute(UPLOAD_ERRORS, ""); session.setAttribute(UPLOAD_FATAL_ERROR, ""); List<String> paths = new ArrayList<String>(); session.setAttribute(FILE_UPLOAD_PATHS, paths); FileUploadListener listener = new FileUploadListener(request.getContentLength()); session.setAttribute(FILE_UPLOAD_STATS, listener.getFileUploadStats()); FileItemFactory factory = new MonitoringFileItemFactory(listener); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = (List<FileItem>) upload.parseRequest(request); startingToSaveUploadedFile(session); String errorMessage = ""; for (FileItem fileItem : items) { if (!fileItem.isFormField() && fileItem.getSize() > 0L) { try { String filename = fileItem.getName(); if (filename.indexOf('/') >= 0) { filename = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.indexOf('\\') >= 0) { filename = filename.substring(filename.lastIndexOf('\\') + 1); } if (!isInWhiteList(filename)) { errorMessage += "The file " + filename + " is not uploaded!"; errorMessage += (StringUtil.isDefined(whiteList) ? " Only " + whiteList.replaceAll(" ", ", ") + " file types can be uploaded<br/>" : " No allowed file format has been defined for upload<br/>"); session.setAttribute(UPLOAD_ERRORS, errorMessage); } else { filename = System.currentTimeMillis() + "-" + filename; File targetDirectory = new File(uploadDir, fileItem.getFieldName()); targetDirectory.mkdirs(); File uploadedFile = new File(targetDirectory, filename); OutputStream out = null; try { out = new FileOutputStream(uploadedFile); IOUtils.copy(fileItem.getInputStream(), out); paths.add(uploadedFile.getParentFile().getName() + '/' + uploadedFile.getName()); } finally { IOUtils.closeQuietly(out); } } } finally { fileItem.delete(); } } } } catch (Exception e) { Logger.getLogger(getClass().getSimpleName()).log(Level.WARNING, e.getMessage()); session.setAttribute(UPLOAD_FATAL_ERROR, "Could not process uploaded file. Please see log for details."); } finally { endingToSaveUploadedFile(session); } }
From source file:azkaban.webapp.servlet.ProjectManagerServlet.java
private void ajaxHandleUpload(HttpServletRequest req, Map<String, String> ret, Map<String, Object> multipart, Session session) throws ServletException, IOException { User user = session.getUser();/*from ww w.j av a 2 s . c o m*/ String projectName = (String) multipart.get("project"); Project project = projectManager.getProject(projectName); String autoFix = (String) multipart.get("fix"); Props props = new Props(); if (autoFix != null && autoFix.equals("off")) { props.put(ValidatorConfigs.CUSTOM_AUTO_FIX_FLAG_PARAM, "false"); } else { props.put(ValidatorConfigs.CUSTOM_AUTO_FIX_FLAG_PARAM, "true"); } if (projectName == null || projectName.isEmpty()) { ret.put("error", "No project name found."); } else if (project == null) { ret.put("error", "Installation Failed. Project '" + projectName + "' doesn't exist."); } else if (!hasPermission(project, user, Type.WRITE)) { ret.put("error", "Installation Failed. User '" + user.getUserId() + "' does not have write access."); } else { ret.put("projectId", String.valueOf(project.getId())); FileItem item = (FileItem) multipart.get("file"); String name = item.getName(); String type = null; final String contentType = item.getContentType(); if (contentType != null && (contentType.startsWith(APPLICATION_ZIP_MIME_TYPE) || contentType.startsWith("application/x-zip-compressed") || contentType.startsWith("application/octet-stream"))) { type = "zip"; } else { item.delete(); ret.put("error", "File type " + contentType + " unrecognized."); return; } File tempDir = Utils.createTempDir(); OutputStream out = null; try { logger.info("Uploading file " + name); File archiveFile = new File(tempDir, name); out = new BufferedOutputStream(new FileOutputStream(archiveFile)); IOUtils.copy(item.getInputStream(), out); out.close(); Map<String, ValidationReport> reports = projectManager.uploadProject(project, archiveFile, type, user, props); StringBuffer errorMsgs = new StringBuffer(); StringBuffer warnMsgs = new StringBuffer(); for (Entry<String, ValidationReport> reportEntry : reports.entrySet()) { ValidationReport report = reportEntry.getValue(); if (!report.getInfoMsgs().isEmpty()) { for (String msg : report.getInfoMsgs()) { switch (ValidationReport.getInfoMsgLevel(msg)) { case ERROR: errorMsgs.append(ValidationReport.getInfoMsg(msg) + "<br/>"); break; case WARN: warnMsgs.append(ValidationReport.getInfoMsg(msg) + "<br/>"); break; default: break; } } } if (!report.getErrorMsgs().isEmpty()) { errorMsgs.append("Validator " + reportEntry.getKey() + " reports errors:<ul>"); for (String msg : report.getErrorMsgs()) { errorMsgs.append("<li>" + msg + "</li>"); } errorMsgs.append("</ul>"); } if (!report.getWarningMsgs().isEmpty()) { warnMsgs.append("Validator " + reportEntry.getKey() + " reports warnings:<ul>"); for (String msg : report.getWarningMsgs()) { warnMsgs.append("<li>" + msg + "</li>"); } warnMsgs.append("</ul>"); } } if (errorMsgs.length() > 0) { // If putting more than 4000 characters in the cookie, the entire // message // will somehow get discarded. ret.put("error", errorMsgs.length() > 4000 ? errorMsgs.substring(0, 4000) : errorMsgs.toString()); } if (warnMsgs.length() > 0) { ret.put("warn", warnMsgs.length() > 4000 ? warnMsgs.substring(0, 4000) : warnMsgs.toString()); } } catch (Exception e) { logger.info("Installation Failed.", e); String error = e.getMessage(); if (error.length() > 512) { error = error.substring(0, 512) + "<br>Too many errors to display.<br>"; } ret.put("error", "Installation Failed.<br>" + error); } finally { if (tempDir.exists()) { FileUtils.deleteDirectory(tempDir); } if (out != null) { out.close(); } } ret.put("version", String.valueOf(project.getVersion())); } }
From source file:com.example.app.ui.vtcrop.VTCropPictureEditor.java
@Nullable private FileItem _getUIValue(@Nullable FileItem uiValue) { if (uiValue == null) { return null; }// www. j a v a 2 s .c om Dimension origDim, newDim; try { origDim = ImageFileUtil.getDimension(uiValue); } catch (IOException e) { _logger.error("Skipping scaling because an error occurred.", e); return uiValue; } if (origDim == null) { _logger.warn("Skipping scaling because retrieved dimension for ui value was null."); return uiValue; } VTCropPictureEditorConfig.ImageScaleOption option = _config.getImageScaleOptionForName(_uiValue.getName()); int newDimWidth = option != null && option.scale != null ? Double.valueOf(_config.getCropWidth() * option.scale).intValue() : _config.getCropWidth(); int newDimHeight = option != null && option.scale != null ? Double.valueOf(_config.getCropHeight() * option.scale).intValue() : _config.getCropHeight(); newDim = ImageFileUtil.getScaledDimension(origDim, newDimWidth, newDimHeight); if (!newDim.equals(origDim)) { _logger.debug("Scale to " + newDim.getWidthMetric() + " x " + newDim.getHeightMetric()); FileItem scaledFileItem = _fileItemFactory.createItem(uiValue.getFieldName(), uiValue.getContentType(), uiValue.isFormField(), uiValue.getName()); try (InputStream is = uiValue.getInputStream(); OutputStream os = scaledFileItem.getOutputStream()) { Thumbnailer tn = Thumbnailer.getInstance(is); BufferedImage scaledImg = tn.getQualityThumbnail(newDim.getWidthMetric().intValue(), newDim.getHeightMetric().intValue()); String extension = StringFactory.getExtension(uiValue.getName()); ImageIO.write(scaledImg, extension, os); uiValue.delete(); uiValue = scaledFileItem; } catch (Throwable e) { _logger.warn("Skipping scaling due to:", e); } } return uiValue; }
From source file:com.example.app.support.ui.vtcrop.VTCropPictureEditor.java
@Nullable private FileItem _getUIValue(@Nullable FileItem uiValue) { if (uiValue == null) { return null; }/* w w w. j ava2 s . c o m*/ Dimension origDim, newDim; try { origDim = ImageFileUtil.getDimension(uiValue); } catch (IOException e) { _logger.error("Skipping scaling because an error occurred.", e); return uiValue; } if (origDim == null) { _logger.warn("Skipping scaling because retrieved dimension for ui value was null."); return uiValue; } VTCropPictureEditorConfig.ImageScaleOption option = _config.getImageScaleOptionForName(_uiValue.getName()); int newDimWidth = option != null && option.scale != null ? Double.valueOf(_config.getCropWidth() * option.scale).intValue() : _config.getCropWidth(); int newDimHeight = option != null && option.scale != null ? Double.valueOf(_config.getCropHeight() * option.scale).intValue() : _config.getCropHeight(); newDim = ImageFileUtil.getScaledDimension(origDim, newDimWidth, newDimHeight); if (!Objects.equals(newDim, origDim)) { _logger.debug("Scale to " + newDim.getWidthMetric() + " x " + newDim.getHeightMetric()); FileItem scaledFileItem = _fileItemFactory.createItem(uiValue.getFieldName(), uiValue.getContentType(), uiValue.isFormField(), uiValue.getName()); try (InputStream is = uiValue.getInputStream(); OutputStream os = scaledFileItem.getOutputStream()) { Thumbnailer tn = Thumbnailer.getInstance(is); BufferedImage scaledImg = tn.getQualityThumbnail(newDim.getWidthMetric().intValue(), newDim.getHeightMetric().intValue()); String extension = StringFactory.getExtension(uiValue.getName()); ImageIO.write(scaledImg, extension, os); uiValue.delete(); uiValue = scaledFileItem; } catch (Throwable e) { _logger.warn("Skipping scaling due to:", e); } } return uiValue; }
From source file:com.weaforce.system.component.fckeditor.connector.ConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * /*from w w w. j a v a 2s . 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"); // "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:hu.sztaki.lpds.pgportal.portlets.workflow.EasyWorkflowPortlet.java
@Override public void doUpload(ActionRequest request, ActionResponse response) { PortletContext context = getPortletContext(); context.log("[FileUploadPortlet] doUpload() called"); try {//from ww w . ja v a 2 s .co m DiskFileItemFactory factory = new DiskFileItemFactory(); PortletFileUpload pfu = new PortletFileUpload(factory); pfu.setSizeMax(uploadMaxSize); // Maximum upload size pfu.setProgressListener((ProgressListener) new FileUploadProgressListener()); PortletSession ps = request.getPortletSession(); if (ps.getAttribute("uploaded") == null) ps.setAttribute("uploaded", new Vector<String>()); ps.setAttribute("upload", pfu); //get the FileItems String fieldName = null; List fileItems = pfu.parseRequest(request); Iterator iter = fileItems.iterator(); File serverSideFile = null; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // retrieve hidden parameters if item is a form field if (item.isFormField()) { fieldName = item.getFieldName(); } else { // item is not a form field, do file upload Hashtable<String, ProgressListener> tmp = (Hashtable<String, ProgressListener>) ps .getAttribute("uploads", ps.APPLICATION_SCOPE); String s = item.getName(); s = FilenameUtils.getName(s); ps.setAttribute("uploading", s); String tempDir = System.getProperty("java.io.tmpdir") + "/uploads/" + request.getRemoteUser(); File f = new File(tempDir); if (!f.exists()) f.mkdirs(); serverSideFile = new File(tempDir, s); item.write(serverSideFile); item.delete(); context.log("[FileUploadPortlet] - file " + s + " uploaded successfully to " + tempDir); // file upload to storage try { Hashtable h = new Hashtable(); h.put("portalURL", PropertyLoader.getInstance().getProperty("service.url")); h.put("userID", request.getRemoteUser()); String uploadField = ""; // retrieve hidden parameters if item is a form field for (FileItem item0 : (List<FileItem>) fileItems) { if (item0.isFormField()) h.put(item0.getFieldName(), item0.getString()); else uploadField = item0.getFieldName(); } Hashtable hsh = new Hashtable(); ServiceType st = InformationBase.getI().getService("storage", "portal", hsh, new Vector()); PortalStorageClient psc = (PortalStorageClient) Class.forName(st.getClientObject()) .newInstance(); psc.setServiceURL(st.getServiceUrl()); psc.setServiceID("/upload"); if (serverSideFile != null) { psc.fileUpload(serverSideFile, uploadField, h); } } catch (Exception ex) { response.setRenderParameter("full", "error.upload"); ex.printStackTrace(); return; } ((Vector<String>) ps.getAttribute("uploaded")).add(s); } } // ps.removeAttribute("uploads",ps.APPLICATION_SCOPE); ps.setAttribute("finaluploads", ""); } catch (SizeLimitExceededException see) { response.setRenderParameter("full", "error.upload.sizelimit"); request.getPortletSession().setAttribute("finaluploads", ""); see.printStackTrace(); context.log("[FileUploadPortlet] - failed to upload file - " + see.toString()); return; } catch (FileUploadException fue) { response.setRenderParameter("full", "error.upload"); fue.printStackTrace(); context.log("[FileUploadPortlet] - failed to upload file - " + fue.toString()); return; } catch (Exception e) { e.printStackTrace(); response.setRenderParameter("full", "error.exception"); context.log("[FileUploadPortlet] - failed to upload file - " + e.toString()); return; } response.setRenderParameter("full", "action.succesfull"); }
From source file:com.yeoou.fckeditor.ConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * /*from www. j a v a 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. */ @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"); }