Example usage for org.apache.commons.fileupload.disk DiskFileItemFactory DiskFileItemFactory

List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory DiskFileItemFactory

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.disk DiskFileItemFactory DiskFileItemFactory.

Prototype

public DiskFileItemFactory(int sizeThreshold, File repository) 

Source Link

Document

Constructs a preconfigured instance of this class.

Usage

From source file:com.qwazr.server.StreamFileUpload.java

public StreamFileUpload(final File repository) {
    super(new DiskFileItemFactory(0, repository));
}

From source file:com.picdrop.guice.provider.implementation.FileItemFactoryProviderImpl.java

protected void init() throws IOException {
    if (this.fac == null) {
        if (!root.exists() || !root.canWrite() || !root.isDirectory()) {
            throw new IOException(String.format("'%s' is not a valid directory", this.root.getAbsolutePath()));
        }//from   www  . ja v  a 2s  . c o m
        DiskFileItemFactory dfac = new DiskFileItemFactory(maxmem, root);
        fac = dfac;
    }
}

From source file:com.github.ikidou.handler.FormHandler.java

@Override
public Object handle(Request request, Response response) throws Exception {
    Map<String, Object> result = new HashMap<>();

    addCustomHeaders(request, result);/*w  w  w  . j  a  v  a 2s. co  m*/

    addQueryParams(request, result);

    if (ServletFileUpload.isMultipartContent(request.raw())) {
        ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory(8, new File("./Data")));
        List<FileItem> fileItems = fileUpload.parseRequest(request.raw());
        List<FileEntity> fileEntities = getFileEntities(result, fileItems);
        if (!fileEntities.isEmpty())
            result.put("_files", fileEntities);
    }

    return result;
}

From source file:com.adanac.module.blog.servlet.UploadImage.java

@Override
protected void service() throws ServletException, IOException {
    HttpServletRequest request = getRequest();
    String path = null;//from w  w w. java  2s.  c  o m
    DiskFileItemFactory factory = new DiskFileItemFactory(5 * 1024,
            new File(Configuration.getContextPath("temp")));
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(3 * 1024 * 1024);
    try {
        List<FileItem> items = upload.parseRequest(request);
        FileItem fileItem = null;
        if (items != null && items.size() > 0 && StringUtils.isNotBlank((fileItem = items.get(0)).getName())) {
            String fileName = fileItem.getName();
            if (!fileName.endsWith(".jpg") && !fileName.endsWith(".gif") && !fileName.endsWith(".png")) {
                writeText("format_error");
                return;
            }
            path = ImageUtil.generatePath(fileItem.getName());
            IOUtil.copy(fileItem.getInputStream(), Configuration.getContextPath(path));
            fileItem.delete();
            writeText(Configuration.getSiteUrl(path));
        }
    } catch (FileUploadException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.krawler.esp.handlers.FileUploadHandler.java

public HashMap getItems(HttpServletRequest request) throws ServiceException {
    HashMap itemMap = null;//  w w  w. ja v  a 2 s. com
    try {
        FileItemFactory factory = new DiskFileItemFactory(4096, new File("/tmp"));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(10485760);//10 mb
        List fileItems = upload.parseRequest(request);
        Iterator iter = fileItems.iterator();
        itemMap = new HashMap();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                itemMap.put(item.getFieldName(), item.getString("UTF-8"));
            } else {
                itemMap.put(item.getFieldName(), item);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw ServiceException.FAILURE("FileUploadHandler.getItems", e);
    }
    return itemMap;
}

From source file:com.fjn.helper.common.io.file.common.FileUpAndDownloadUtil.java

/**
 * ???????/*from   w w w . jav a  2  s  . co m*/
 * @param klass   ???klass?Class
 * @param filepath   ?
 * @param sizeThreshold   ??
 * @param isFileNameBaseTime   ????
 * @return bean
 */
public static <T> Object upload(HttpServletRequest request, Class<T> klass, String filepath, int sizeThreshold,
        boolean isFileNameBaseTime) throws Exception {
    FileItemFactory fileItemFactory = null;
    if (sizeThreshold > 0) {
        File repository = new File(filepath);
        fileItemFactory = new DiskFileItemFactory(sizeThreshold, repository);
    } else {
        fileItemFactory = new DiskFileItemFactory();
    }
    ServletFileUpload upload = new ServletFileUpload(fileItemFactory);
    ServletRequestContext requestContext = new ServletRequestContext(request);
    T bean = null;
    if (klass != null) {
        bean = klass.newInstance();
    }
    // 
    if (ServletFileUpload.isMultipartContent(requestContext)) {
        File parentDir = new File(filepath);

        List<FileItem> fileItemList = upload.parseRequest(requestContext);
        for (int i = 0; i < fileItemList.size(); i++) {
            FileItem item = fileItemList.get(i);
            // ??
            if (item.isFormField()) {
                String paramName = item.getFieldName();
                String paramValue = item.getString("UTF-8");
                log.info("?" + paramName + "=" + paramValue);
                request.setAttribute(paramName, paramValue);
                // ?bean
                if (klass != null) {
                    Field field = null;
                    try {
                        field = klass.getDeclaredField(paramName);

                        if (field != null) {
                            field.setAccessible(true);
                            Class type = field.getType();
                            if (type == Integer.TYPE) {
                                field.setInt(bean, Integer.valueOf(paramValue));
                            } else if (type == Double.TYPE) {
                                field.setDouble(bean, Double.valueOf(paramValue));
                            } else if (type == Float.TYPE) {
                                field.setFloat(bean, Float.valueOf(paramValue));
                            } else if (type == Boolean.TYPE) {
                                field.setBoolean(bean, Boolean.valueOf(paramValue));
                            } else if (type == Character.TYPE) {
                                field.setChar(bean, paramValue.charAt(0));
                            } else if (type == Long.TYPE) {
                                field.setLong(bean, Long.valueOf(paramValue));
                            } else if (type == Short.TYPE) {
                                field.setShort(bean, Short.valueOf(paramValue));
                            } else {
                                field.set(bean, paramValue);
                            }
                        }
                    } catch (NoSuchFieldException e) {
                        log.info("" + klass.getName() + "?" + paramName);
                    }
                }
            }
            // 
            else {
                // <input type='file' name='xxx'> xxx
                String paramName = item.getFieldName();
                log.info("?" + item.getSize());

                if (sizeThreshold > 0) {
                    if (item.getSize() > sizeThreshold)
                        continue;
                }
                String clientFileName = item.getName();
                int index = -1;
                // ?IE?
                if ((index = clientFileName.lastIndexOf("\\")) != -1) {
                    clientFileName = clientFileName.substring(index + 1);
                }
                if (clientFileName == null || "".equals(clientFileName))
                    continue;

                String filename = null;
                log.info("" + paramName + "\t??" + clientFileName);
                if (isFileNameBaseTime) {
                    filename = buildFileName(clientFileName);
                } else
                    filename = clientFileName;

                request.setAttribute(paramName, filename);

                // ?bean
                if (klass != null) {
                    Field field = null;
                    try {
                        field = klass.getDeclaredField(paramName);
                        if (field != null) {
                            field.setAccessible(true);
                            field.set(bean, filename);
                        }
                    } catch (NoSuchFieldException e) {
                        log.info("" + klass.getName() + "?  " + paramName);
                        continue;
                    }
                }

                if (!parentDir.exists()) {
                    parentDir.mkdirs();
                }

                File newfile = new File(parentDir, filename);
                item.write(newfile);
                String serverPath = newfile.getPath();
                log.info("?" + serverPath);
            }
        }
    }
    return bean;
}

From source file:com.threecrickets.prudence.util.FormWithFiles.java

/**
 * Constructor.//w  w  w . j a  v a2 s .c  o  m
 * 
 * @param webForm
 *        The URL encoded web form
 * @param sizeThreshold
 *        The size in bytes beyond which files will be stored to disk
 * @param repositoryDirectory
 *        The directory in which to place uploaded files
 * @throws ResourceException
 *         In case of an upload handling error
 */
public FormWithFiles(Representation webForm, int sizeThreshold, File repositoryDirectory)
        throws ResourceException {
    this(webForm, new DiskFileItemFactory(sizeThreshold, repositoryDirectory));
}

From source file:com.threecrickets.prudence.util.PhpExecutionController.java

/**
 * Constructor.//from   www .  j  av a  2s  . c om
 * 
 * @param sizeThreshold
 *        The size in bytes beyond which files will be stored to disk
 * @param repositoryDirectory
 *        The directory in which to place uploaded files
 */
public PhpExecutionController(int sizeThreshold, File repositoryDirectory) {
    this(new DiskFileItemFactory(sizeThreshold, repositoryDirectory));
}

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;/*from w  w  w  .j  a v  a  2  s  .c  o  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:fr.aliasource.webmail.server.UploadAttachmentsImpl.java

@SuppressWarnings("rawtypes")
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    RequestContext ctx = new ServletRequestContext(req);
    String enc = ctx.getCharacterEncoding();
    logger.warn("received encoding is " + enc);
    if (enc == null) {
        enc = "utf-8";
    }/*from   w w w  . j  a va2  s .c  om*/
    IAccount account = (IAccount) req.getSession().getAttribute("account");

    if (account == null) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    DiskFileItemFactory factory = new DiskFileItemFactory(100 * 1024,
            new File(System.getProperty("java.io.tmpdir")));
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(20 * 1024 * 1024);

    List items = null;
    try {
        items = upload.parseRequest(req);
    } catch (FileUploadException e1) {
        logger.error("upload exception", e1);
        return;
    }

    // Process the uploaded items
    String id = null;
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (!item.isFormField()) {
            id = item.getFieldName();
            String fileName = removePathElementsFromFilename(item.getName());
            logger.warn("FileItem: " + item);
            long size = item.getSize();
            logger.warn("pushing upload of " + fileName + " to backend for " + account.getLogin() + "@"
                    + account.getDomain() + " size: " + size + ").");
            AttachmentMetadata meta = new AttachmentMetadata();
            meta.setFileName(fileName);
            meta.setSize(size);
            meta.setMime(item.getContentType());
            try {
                account.uploadAttachement(id, meta, item.getInputStream());
            } catch (Exception e) {
                logger.error("Cannot write uploaded file to disk");
            }
        }
    }
}