Example usage for org.apache.commons.fileupload.servlet ServletFileUpload setHeaderEncoding

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload setHeaderEncoding

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload setHeaderEncoding.

Prototype

public void setHeaderEncoding(String encoding) 

Source Link

Document

Specifies the character encoding to be used when reading the headers of individual parts.

Usage

From source file:echopoint.tucana.JakartaCommonsFileUploadProvider.java

/**
 * @see UploadSPI#handleUpload(nextapp.echo.webcontainer.Connection ,
 *      FileUploadSelector, String, UploadProgress)
 *///ww w .  j a v a2s .  c  o  m
@SuppressWarnings({ "ThrowableInstanceNeverThrown" })
public void handleUpload(final Connection conn, final FileUploadSelector uploadSelect, final String uploadIndex,
        final UploadProgress progress) throws Exception {
    final ApplicationInstance app = conn.getUserInstance().getApplicationInstance();

    final DiskFileItemFactory itemFactory = new DiskFileItemFactory();
    itemFactory.setRepository(getDiskCacheLocation());
    itemFactory.setSizeThreshold(getMemoryCacheThreshold());

    String encoding = conn.getRequest().getCharacterEncoding();
    if (encoding == null) {
        encoding = "UTF-8";
    }

    final ServletFileUpload upload = new ServletFileUpload(itemFactory);
    upload.setHeaderEncoding(encoding);
    upload.setProgressListener(new UploadProgressListener(progress));

    long sizeLimit = uploadSelect.getUploadSizeLimit();
    if (sizeLimit == 0)
        sizeLimit = getFileUploadSizeLimit();
    if (sizeLimit != NO_SIZE_LIMIT) {
        upload.setSizeMax(sizeLimit);
    }

    String fileName = null;
    String contentType = null;

    try {
        final FileItemIterator iter = upload.getItemIterator(conn.getRequest());
        if (iter.hasNext()) {
            final FileItemStream stream = iter.next();

            if (!stream.isFormField()) {
                fileName = FilenameUtils.getName(stream.getName());
                contentType = stream.getContentType();

                final Set<String> types = uploadSelect.getContentTypeFilter();
                if (!types.isEmpty()) {
                    if (!types.contains(contentType)) {
                        app.enqueueTask(uploadSelect.getTaskQueue(), new InvalidContentTypeRunnable(
                                uploadSelect, uploadIndex, fileName, contentType, progress));
                        return;
                    }
                }

                progress.setStatus(Status.inprogress);
                final FileItem item = itemFactory.createItem(fileName, contentType, false, stream.getName());
                item.getOutputStream(); // initialise DiskFileItem internals

                uploadSelect.notifyCallback(
                        new UploadStartEvent(uploadSelect, uploadIndex, fileName, contentType, item.getSize()));

                IOUtils.copy(stream.openStream(), item.getOutputStream());

                app.enqueueTask(uploadSelect.getTaskQueue(),
                        new FinishRunnable(uploadSelect, uploadIndex, fileName, item, progress));

                return;
            }
        }

        app.enqueueTask(uploadSelect.getTaskQueue(), new FailRunnable(uploadSelect, uploadIndex, fileName,
                contentType, new RuntimeException("No multi-part content!"), progress));
    } catch (final FileUploadBase.SizeLimitExceededException e) {
        app.enqueueTask(uploadSelect.getTaskQueue(), new FailRunnable(uploadSelect, uploadIndex, fileName,
                contentType, new UploadSizeLimitExceededException(e), progress));
    } catch (final FileUploadBase.FileSizeLimitExceededException e) {
        app.enqueueTask(uploadSelect.getTaskQueue(), new FailRunnable(uploadSelect, uploadIndex, fileName,
                contentType, new UploadSizeLimitExceededException(e), progress));
    } catch (final MultipartStream.MalformedStreamException e) {
        app.enqueueTask(uploadSelect.getTaskQueue(),
                new CancelRunnable(uploadSelect, uploadIndex, fileName, contentType, e, progress));
    }
}

From source file:com.openkm.extension.servlet.ZohoFileUploadServlet.java

@SuppressWarnings("unchecked")
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.info("service({}, {})", request, response);
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    InputStream is = null;//from w w  w  .  j  a v a2  s .  com
    String id = "";

    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");

        // Parse the request and get all parameters and the uploaded file
        List<FileItem> items;

        try {
            items = upload.parseRequest(request);
            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();
                if (item.isFormField()) {
                    // if (item.getFieldName().equals("format")) { format =
                    // item.getString("UTF-8"); }
                    if (item.getFieldName().equals("id")) {
                        id = item.getString("UTF-8");
                    }
                    // if (item.getFieldName().equals("filename")) {
                    // filename = item.getString("UTF-8"); }
                } else {
                    is = item.getInputStream();
                }
            }

            // Retrieve token
            ZohoToken zot = ZohoTokenDAO.findByPk(id);

            // Save document
            if (Config.REPOSITORY_NATIVE) {
                String sysToken = DbSessionManager.getInstance().getSystemToken();
                String path = OKMRepository.getInstance().getNodePath(sysToken, zot.getNode());
                new DbDocumentModule().checkout(sysToken, path, zot.getUser());
                new DbDocumentModule().checkin(sysToken, path, is, "Modified from Zoho", zot.getUser());
            } else {
                String sysToken = JcrSessionManager.getInstance().getSystemToken();
                String path = OKMRepository.getInstance().getNodePath(sysToken, zot.getNode());
                new JcrDocumentModule().checkout(sysToken, path, zot.getUser());
                new JcrDocumentModule().checkin(sysToken, path, is, "Modified from Zoho", zot.getUser());
            }
        } catch (FileUploadException e) {
            log.error(e.getMessage(), e);
        } catch (PathNotFoundException e) {
            log.error(e.getMessage(), e);
        } catch (RepositoryException e) {
            log.error(e.getMessage(), e);
        } catch (DatabaseException e) {
            log.error(e.getMessage(), e);
        } catch (FileSizeExceededException e) {
            log.error(e.getMessage(), e);
        } catch (UserQuotaExceededException e) {
            log.error(e.getMessage(), e);
        } catch (VirusDetectedException e) {
            log.error(e.getMessage(), e);
        } catch (VersionException e) {
            log.error(e.getMessage(), e);
        } catch (LockException e) {
            log.error(e.getMessage(), e);
        } catch (AccessDeniedException e) {
            log.error(e.getMessage(), e);
        } catch (ExtensionException e) {
            log.error(e.getMessage(), e);
        } catch (AutomationException e) {
            log.error(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
}

From source file:es.eucm.mokap.backend.server.MokapBackend.java

/**
 * Iterates the whole request in search for a file. When it finds it, it
 * creates a FileItemStream which contains it.
 * //from  w  w  w.j av  a  2 s .c  om
 * @param req
 *            The request to process
 * @return Returns THE FIRST file found in the upload request or null if no
 *         file could be found
 */
private FileItemStream getUploadedFile(HttpServletRequest req) throws IOException, FileUploadException {
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();
    // Set the UTF-8 encoding to grab the correct uploaded filename,
    // especially for Chinese
    upload.setHeaderEncoding("UTF-8");

    FileItemStream file = null;

    /* Parse the request */
    FileItemIterator iter = upload.getItemIterator(req);
    while (iter.hasNext()) {
        FileItemStream item = iter.next();
        if (!item.isFormField()) {
            file = item;
            break;
        }
    }
    return file;
}

From source file:com.hzc.framework.ssh.controller.WebUtil.java

/**
 *  //w w w.ja v  a 2s  .  c  o  m
 *
 * @param path
 * @param ufc
 * @return
 * @throws Exception
 */
public static void uploadMulti(String path, UploadFileCall ufc) throws RuntimeException {
    try {
        HttpServletRequest request = getReq();
        ServletContext servletContext = getServletContext();
        File file = new File(servletContext.getRealPath(path));
        if (!file.exists())
            file.mkdir();
        DiskFileItemFactory fac = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setHeaderEncoding("UTF-8");
        List<FileItem> fileItems = upload.parseRequest(request);
        for (FileItem item : fileItems) {
            if (!item.isFormField()) {
                String name = item.getName();
                String type = item.getContentType();
                if (StringUtils.isNotBlank(name)) {
                    File f = new File(file + File.separator + name);
                    item.write(f);
                    ufc.file(null, f, name, name, type);
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.primeleaf.krystal.web.action.console.UpdateProfilePictureAction.java

@SuppressWarnings("rawtypes")
public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    request.setCharacterEncoding(HTTPConstants.CHARACTER_ENCODING);
    HttpSession session = request.getSession();
    User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL);
    if (request.getMethod().equalsIgnoreCase("POST")) {
        try {/*  www. j  av  a 2 s .  c om*/
            String userName = loggedInUser.getUserName();
            String sessionid = (String) session.getId();

            String tempFilePath = System.getProperty("java.io.tmpdir");

            if (!(tempFilePath.endsWith("/") || tempFilePath.endsWith("\\"))) {
                tempFilePath += System.getProperty("file.separator");
            }
            tempFilePath += userName + "_" + sessionid;

            //variables
            String fileName = "", ext = "";
            File file = null;
            // Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            request.setCharacterEncoding(HTTPConstants.CHARACTER_ENCODING);
            upload.setHeaderEncoding(HTTPConstants.CHARACTER_ENCODING);
            List listItems = upload.parseRequest((HttpServletRequest) request);

            Iterator iter = listItems.iterator();
            FileItem fileItem = null;
            while (iter.hasNext()) {
                fileItem = (FileItem) iter.next();
                if (!fileItem.isFormField()) {
                    try {
                        fileName = fileItem.getName();
                        file = new File(fileName);
                        fileName = file.getName();
                        ext = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase();
                        if (!"JPEG".equalsIgnoreCase(ext) && !"JPG".equalsIgnoreCase(ext)
                                && !"PNG".equalsIgnoreCase(ext)) {
                            request.setAttribute(HTTPConstants.REQUEST_ERROR,
                                    "Invalid image. Please upload JPG or PNG file");
                            return (new MyProfileAction().execute(request, response));
                        }
                        file = new File(tempFilePath + "." + ext);
                        fileItem.write(file);
                    } catch (Exception ex) {
                        session.setAttribute("UPLOAD_ERROR", ex.getLocalizedMessage());
                        return (new MyProfileAction().execute(request, response));
                    }
                }
            } //if

            if (file.length() <= 0) { //code for checking minimum size of file
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Zero length document");
                return (new MyProfileAction().execute(request, response));
            }
            if (file.length() > (1024 * 1024 * 2)) { //code for checking minimum size of file
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Image size too large. Upload upto 2MB file");
                return (new MyProfileAction().execute(request, response));
            }

            User user = loggedInUser;
            user.setProfilePicture(file);
            UserDAO.getInstance().setProfilePicture(user);

            AuditLogManager.log(new AuditLogRecord(user.getUserId(), AuditLogRecord.OBJECT_USER,
                    AuditLogRecord.ACTION_EDITED, loggedInUser.getUserName(), request.getRemoteAddr(),
                    AuditLogRecord.LEVEL_INFO, "", "Profile picture update"));
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    }
    request.setAttribute(HTTPConstants.REQUEST_MESSAGE, "Profile picture uploaded successfully");
    return (new MyProfileAction().execute(request, response));
}

From source file:com.hzc.framework.ssh.controller.WebUtil.java

/**
 * jsonp?// w  w  w .  j a v a 2s . com
 *  + ?
 *
 * @param path
 * @param ufc
 * @return
 * @throws Exception
 */
public static <T> T uploadMultiAndProgress(String path, Class<T> c, UploadFileNewCall ufc,
        final ProgressListener pl) throws RuntimeException {
    try {
        HttpServletRequest request = getReq();
        //            final HttpSession session = getSession();
        ServletContext servletContext = getServletContext();
        File file = new File(servletContext.getRealPath(path));
        if (!file.exists())
            file.mkdir();

        DiskFileItemFactory fac = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setHeaderEncoding("UTF-8");
        upload.setProgressListener(pl);
        List<FileItem> fileItems = upload.parseRequest(request);

        T obj = c.newInstance();
        Field[] declaredFields = c.getDeclaredFields();
        for (FileItem item : fileItems) {
            if (!item.isFormField()) {

                String name = item.getName();
                String type = item.getContentType();
                if (StringUtils.isNotBlank(name)) {
                    File f = new File(file + File.separator + name);
                    item.write(f);
                    ufc.file(obj, f, name, name, item.getSize(), type); // ????
                }
            } else {

                String name = item.getFieldName();
                // ??,??
                for (Field field : declaredFields) {
                    field.setAccessible(true);
                    String fieldName = field.getName();
                    if (name.equals(fieldName)) {
                        String value = item.getString("UTF-8");
                        if (null == value) {
                            continue;
                        }
                        Class<?> type = field.getType();
                        if (type == Long.class) {
                            field.set(obj, Long.parseLong(value));
                        } else if (type == String.class) {
                            field.set(obj, value);
                        } else if (type == Byte.class) {
                            field.set(obj, Byte.parseByte(value));
                        } else if (type == Integer.class) {
                            field.set(obj, Integer.parseInt(value));
                        } else if (type == Character.class) {
                            field.set(obj, value.charAt(0));
                        } else if (type == Boolean.class) {
                            field.set(obj, Boolean.parseBoolean(value));
                        } else if (type == Double.class) {
                            field.set(obj, Double.parseDouble(value));
                        } else if (type == Float.class) {
                            field.set(obj, Float.parseFloat(value));
                        }
                    }
                }
            }
        }
        return obj;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:edu.umn.msi.tropix.webgui.server.UploadController.java

@ServiceMethod(secure = true)
public ModelAndView handleRequest(final HttpServletRequest request, final HttpServletResponse response)
        throws Exception {
    LOG.debug("In UploadController.handleRequest");
    //final String userId = securityProvider.getUserIdForSessionId(request.getParameter("sessionId"));
    //Preconditions.checkState(userId != null);
    final String userId = userSession.getGridId();
    LOG.debug("Upload by user with id " + userId);
    String clientId = request.getParameter("clientId");
    if (!StringUtils.hasText(clientId)) {
        clientId = UUID.randomUUID().toString();
    }//from   w  w  w  .j av  a  2  s.  c  o m
    final String endStr = request.getParameter("end");
    final String startStr = request.getParameter("start");
    final String zipStr = request.getParameter("zip");

    final String lastUploadStr = request.getParameter("lastUpload");
    final boolean isZip = StringUtils.hasText("zip") ? Boolean.parseBoolean(zipStr) : false;
    final boolean lastUploads = StringUtils.hasText(lastUploadStr) ? Boolean.parseBoolean(lastUploadStr) : true;

    LOG.trace("Upload request with startStr " + startStr);
    final StringWriter rawJsonWriter = new StringWriter();
    final JSONWriter jsonWriter = new JSONWriter(rawJsonWriter);
    final FileItemFactory factory = new DiskFileItemFactory();

    final long requestLength = StringUtils.hasText(endStr) ? Long.parseLong(endStr)
            : request.getContentLength();
    long bytesWritten = StringUtils.hasText(startStr) ? Long.parseLong(startStr) : 0L;

    final ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8"); // Deal with international file names
    final FileItemIterator iter = upload.getItemIterator(request);

    // Setup message conditionalSampleComponent to track upload progress...
    final ProgressMessageSupplier supplier = new ProgressMessageSupplier();
    supplier.setId(userId + "/" + clientId);
    supplier.setName("Upload File(s) to Web Application");

    final ProgressTrackerImpl progressTracker = new ProgressTrackerImpl();
    progressTracker.setUserGridId(userId);
    progressTracker.setCometPusher(cometPusher);
    progressTracker.setProgressMessageSupplier(supplier);

    jsonWriter.object();
    jsonWriter.key("result");
    jsonWriter.array();

    while (iter.hasNext()) {
        final FileItemStream item = iter.next();
        if (item.isFormField()) {
            continue;
        }
        File destination;
        InputStream inputStream = null;
        OutputStream outputStream = null;

        if (!isZip) {
            final String fileName = FilenameUtils.getName(item.getName()); // new File(item.getName()).getName();
            LOG.debug("Handling upload of file with name " + fileName);

            final TempFileInfo info = tempFileStore.getTempFileInfo(fileName);
            recordJsonInfo(jsonWriter, info);
            destination = info.getTempLocation();
        } else {
            destination = FILE_UTILS.createTempFile();
        }

        try {
            inputStream = item.openStream();
            outputStream = FILE_UTILS.getFileOutputStream(destination);
            bytesWritten += progressTrackingIoUtils.copy(inputStream, outputStream, bytesWritten, requestLength,
                    progressTracker);

            if (isZip) {
                ZipUtilsFactory.getInstance().unzip(destination, new Function<String, File>() {
                    public File apply(final String fileName) {
                        final String cleanedUpFileName = FilenameUtils.getName(fileName);
                        final TempFileInfo info = tempFileStore.getTempFileInfo(cleanedUpFileName);
                        recordJsonInfo(jsonWriter, info);
                        return info.getTempLocation();
                    }
                });
            }
        } finally {
            IO_UTILS.closeQuietly(inputStream);
            IO_UTILS.closeQuietly(outputStream);
            if (isZip) {
                FILE_UTILS.deleteQuietly(destination);
            }
        }
    }
    if (lastUploads) {
        progressTracker.complete();
    }
    jsonWriter.endArray();
    jsonWriter.endObject();
    // response.setStatus(200);
    final String json = rawJsonWriter.getBuffer().toString();
    LOG.debug("Upload json response " + json);
    response.setContentType("text/html"); // GWT was attaching <pre> tag to result without this
    response.getOutputStream().println(json);
    return null;
}

From source file:com.googlecode.psiprobe.controllers.deploy.UploadWarController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    if (FileUpload.isMultipartContent(new ServletRequestContext(request))) {

        File tmpWar = null;// ww  w.  j ava  2 s.  co m
        String contextName = null;
        boolean update = false;
        boolean compile = false;
        boolean discard = false;

        //
        // parse multipart request and extract the file
        //
        FileItemFactory factory = new DiskFileItemFactory(1048000,
                new File(System.getProperty("java.io.tmpdir")));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(-1);
        upload.setHeaderEncoding("UTF8");
        try {
            for (Iterator it = upload.parseRequest(request).iterator(); it.hasNext();) {
                FileItem fi = (FileItem) it.next();
                if (!fi.isFormField()) {
                    if (fi.getName() != null && fi.getName().length() > 0) {
                        tmpWar = new File(System.getProperty("java.io.tmpdir"),
                                FilenameUtils.getName(fi.getName()));
                        fi.write(tmpWar);
                    }
                } else if ("context".equals(fi.getFieldName())) {
                    contextName = fi.getString();
                } else if ("update".equals(fi.getFieldName()) && "yes".equals(fi.getString())) {
                    update = true;
                } else if ("compile".equals(fi.getFieldName()) && "yes".equals(fi.getString())) {
                    compile = true;
                } else if ("discard".equals(fi.getFieldName()) && "yes".equals(fi.getString())) {
                    discard = true;
                }
            }
        } catch (Exception e) {
            logger.fatal("Could not process file upload", e);
            request.setAttribute("errorMessage", getMessageSourceAccessor()
                    .getMessage("probe.src.deploy.war.uploadfailure", new Object[] { e.getMessage() }));
            if (tmpWar != null && tmpWar.exists()) {
                tmpWar.delete();
            }
            tmpWar = null;
        }

        String errMsg = null;

        if (tmpWar != null) {
            try {
                if (tmpWar.getName().endsWith(".war")) {

                    if (contextName == null || contextName.length() == 0) {
                        String warFileName = tmpWar.getName().replaceAll("\\.war$", "");
                        contextName = "/" + warFileName;
                    }

                    contextName = getContainerWrapper().getTomcatContainer().formatContextName(contextName);

                    //
                    // pass the name of the newly deployed context to the presentation layer
                    // using this name the presentation layer can render a url to view compilation details
                    //
                    String visibleContextName = "".equals(contextName) ? "/" : contextName;
                    request.setAttribute("contextName", visibleContextName);

                    if (update && getContainerWrapper().getTomcatContainer().findContext(contextName) != null) {
                        logger.debug("updating " + contextName + ": removing the old copy");
                        getContainerWrapper().getTomcatContainer().remove(contextName);
                    }

                    if (getContainerWrapper().getTomcatContainer().findContext(contextName) == null) {
                        //
                        // move the .war to tomcat application base dir
                        //
                        String destWarFilename = getContainerWrapper().getTomcatContainer()
                                .formatContextFilename(contextName);
                        File destWar = new File(getContainerWrapper().getTomcatContainer().getAppBase(),
                                destWarFilename + ".war");

                        FileUtils.moveFile(tmpWar, destWar);

                        //
                        // let Tomcat know that the file is there
                        //
                        getContainerWrapper().getTomcatContainer().installWar(contextName,
                                new URL("jar:" + destWar.toURI().toURL().toString() + "!/"));

                        Context ctx = getContainerWrapper().getTomcatContainer().findContext(contextName);
                        if (ctx == null) {
                            errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notinstalled",
                                    new Object[] { visibleContextName });
                        } else {
                            request.setAttribute("success", Boolean.TRUE);
                            if (discard) {
                                getContainerWrapper().getTomcatContainer().discardWorkDir(ctx);
                            }
                            if (compile) {
                                Summary summary = new Summary();
                                summary.setName(ctx.getName());
                                getContainerWrapper().getTomcatContainer().listContextJsps(ctx, summary, true);
                                request.getSession(true).setAttribute(DisplayJspController.SUMMARY_ATTRIBUTE,
                                        summary);
                                request.setAttribute("compileSuccess", Boolean.TRUE);
                            }
                        }

                    } else {
                        errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.alreadyExists",
                                new Object[] { visibleContextName });
                    }
                } else {
                    errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notWar.failure");
                }
            } catch (Exception e) {
                errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.failure",
                        new Object[] { e.getMessage() });
                logger.error("Tomcat throw an exception when trying to deploy", e);
            } finally {
                if (errMsg != null) {
                    request.setAttribute("errorMessage", errMsg);
                }
                tmpWar.delete();
            }
        }
    }
    return new ModelAndView(new InternalResourceView(getViewName()));
}

From source file:com.eryansky.common.web.servlet.kindeditor.FileUploadServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String dirName = request.getParameter("dir");
    if (dirName == null) {
        dirName = "image";
    }//from w  w  w  .j a  va  2s.  co  m

    //?
    String uploadPath = getInitParameter("UPLOAD_PATH");
    if (StringUtils.isNotBlank(uploadPath)) {
        configPath = uploadPath;
    }

    if ("image".equals(dirName)) {

        //?
        Long size = Long.parseLong(getInitParameter("Img_MAX_SIZE"));
        if (size != null) {
            maxSize = size;
        }

        //(?gif, jpg, jpeg, png, bmp)
        String type = getInitParameter("Img_YPES");
        if (StringUtils.isNotBlank(type)) {
            extMap.put("image", type);
        }

    } else {
        //?
        Long size = Long.parseLong(getInitParameter("File_MAX_SIZE"));
        if (size != null) {
            maxSize = size;
        }

        if ("file".equals(dirName)) {
            //(doc, xls, ppt, pdf, txt, rar, zip)
            String type = getInitParameter("File_TYPES");
            if (StringUtils.isNotBlank(type)) {
                extMap.put("file", type);
            }
        }
    }

    if (StringUtils.isBlank(configPath)) {
        ServletUtils.renderText(getError("?!"), response);
        return;
    }

    //?
    String savePath = this.getServletContext().getRealPath("/") + configPath;

    //?URL
    String saveUrl = request.getContextPath() + "/" + configPath;

    if (!ServletFileUpload.isMultipartContent(request)) {
        ServletUtils.renderText(getError(""), response);
        return;
    }
    //
    File uploadDir = new File(savePath);
    if (!uploadDir.isDirectory()) {
        FileUtil.createDirectory(uploadDir.getPath());
        //         ServletUtils.rendText(getError("?"), response);
        //         return;
    }
    //??
    if (!uploadDir.canWrite()) {
        ServletUtils.renderText(getError("??"), response);
        return;
    }

    if (!extMap.containsKey(dirName)) {
        ServletUtils.renderText(getError("???"), response);
        return;
    }
    //
    savePath += dirName + "/";
    saveUrl += dirName + "/";
    File saveDirFile = new File(savePath);
    if (!saveDirFile.exists()) {
        saveDirFile.mkdirs();
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    String ymd = sdf.format(new Date());
    savePath += ymd + "/";
    saveUrl += ymd + "/";
    File dirFile = new File(savePath);
    if (!dirFile.exists()) {
        dirFile.mkdirs();
    }

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");

    try {
        List items = upload.parseRequest(request);
        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            String fileName = item.getName();
            long fileSize = item.getSize();
            if (!item.isFormField()) {
                //?
                if (item.getSize() > maxSize) {
                    ServletUtils.renderText(getError("??"), response);
                    return;
                }
                //??
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                if (!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)) {
                    ServletUtils
                            .renderText(getError("??????\n??"
                                    + extMap.get(dirName) + "?"), response);
                    return;
                }

                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                try {
                    File uploadedFile = new File(savePath, newFileName);
                    item.write(uploadedFile);
                } catch (Exception e) {
                    ServletUtils.renderText(getError(""), response);
                    return;
                }

                Map<String, Object> obj = Maps.newHashMap();
                obj.put("error", 0);
                obj.put("url", saveUrl + newFileName);
                ServletUtils.renderText(obj, response);
            }
        }
    } catch (FileUploadException e1) {
        e1.printStackTrace();
    }

}

From source file:cc.aileron.wsgi.request.WsgiRequestParameterFactoryImpl.java

@Override
public WorkflowRequestParameter create(final HttpServletRequest request) throws FileUploadException {
    try {//  w  ww.  j  a v  a 2 s.com
        request.setCharacterEncoding(characterEncodingName);
    } catch (final UnsupportedEncodingException e) {
    }
    if (ServletFileUpload.isMultipartContent(request)) {
        final DiskFileItemFactory factory = new DiskFileItemFactory();
        final ServletFileUpload upload = new ServletFileUpload(factory);
        factory.setSizeThreshold(1024);
        upload.setSizeMax(-1);
        upload.setHeaderEncoding(characterEncodingName);
        return new RequestMultipart(characterEncoding, upload, request);
    }
    return new RequestUrlencoded(request);
}