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

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

Introduction

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

Prototype

public void setRepository(File repository) 

Source Link

Document

Sets the directory used to temporarily store files that are larger than the configured size threshold.

Usage

From source file:kelly.core.argument.CommonsFileUploadActionArgumentResolver.java

@Override
public Object resolve(ActionArgument actionArgument, Castor castor) {
    Multipart annotation = actionArgument.getAnnotation(Multipart.class);

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository("".equals(annotation.tempdir()) ? DEFAULT_TEMP_DIR : new File(annotation.tempdir()));
    factory.setSizeThreshold(annotation.sizeThreshold());

    ServletFileUpload upload = new ServletFileUpload(factory);

    upload.setSizeMax(annotation.maxSize());

    try {//ww w. j a  v a  2s .c om
        List<FileItem> items = upload.parseRequest(WebContextHolder.getInstance().getRequest());
        return items.toArray(new FileItem[items.size()]);
    } catch (FileUploadException e) {
        throw new kelly.core.exception.FileUploadException(e);
    }
}

From source file:com.jyhon.servlet.audit.AuditUserServlet.java

private List<FileItem> getFileItems(HttpServletRequest request, String pathTemp) {
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    diskFileItemFactory.setRepository(new File(pathTemp));
    diskFileItemFactory.setSizeThreshold(10240);
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    List<FileItem> items = null;
    try {//  w  w w .j a v a  2 s. c  o m
        items = servletFileUpload.parseRequest(request);
    } catch (FileUploadException e) {
        e.printStackTrace();
    }
    return items;
}

From source file:com.pamarin.servlet.uploadfile.UploadFileServet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.log(Level.INFO, "uploaded");

    try {// w ww .ja  v a  2s . c o m
        if (!ServletFileUpload.isMultipartContent(request)) {
            return;
        }

        LOG.log(Level.INFO, "is multipart");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(maxMemSize);
        factory.setRepository(new File("c:\\temp"));
        //
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxFileSize);

        List<FileItem> fileItems = upload.parseRequest(request);
        Iterator<FileItem> iterator = fileItems.iterator();

        LOG.log(Level.INFO, "file size --> {0}", fileItems.size());
        while (iterator.hasNext()) {
            FileItem item = iterator.next();
            //if (!item.isFormField()) {
            LOG.log(Level.INFO, "content type --> {0}", item.getContentType());
            LOG.log(Level.INFO, "name --> {0}", item.getName());
            LOG.log(Level.INFO, "field name --> {0}", item.getFieldName());
            LOG.log(Level.INFO, "string --> {0}", item.getString());

            item.write(new File("c:\\temp", UUID.randomUUID().toString() + ".png"));
            //}
        }
    } catch (FileUploadException ex) {
        LOG.log(Level.WARNING, ex.getMessage());
    } catch (Exception ex) {
        LOG.log(Level.WARNING, ex.getMessage());
    }
}

From source file:com.sketchy.server.UpgradeUploadServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    JSONServletResult jsonServletResult = new JSONServletResult(Status.SUCCESS);
    try {/*w ww  .  j  a  v  a  2  s.c  om*/

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setRepository(FileUtils.getTempDirectory());
            factory.setSizeThreshold(MAX_SIZE);

            ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
            List<FileItem> files = servletFileUpload.parseRequest(request);
            String version = "";
            for (FileItem fileItem : files) {
                String uploadFileName = fileItem.getName();
                if (StringUtils.isNotBlank(uploadFileName)) {

                    JarInputStream jarInputStream = null;
                    try {
                        // check to make sure it's a Sketchy File with a Manifest File
                        jarInputStream = new JarInputStream(fileItem.getInputStream(), true);
                        Manifest manifest = jarInputStream.getManifest();
                        if (manifest == null) {
                            throw new Exception("Invalid Upgrade File!");
                        }
                        Attributes titleAttributes = manifest.getMainAttributes();
                        if ((titleAttributes == null) || (!StringUtils.containsIgnoreCase(
                                titleAttributes.getValue("Implementation-Title"), "Sketchy"))) {
                            throw new Exception("Invalid Upgrade File!");
                        }
                        version = titleAttributes.getValue("Implementation-Version");
                    } catch (Exception e) {
                        throw new Exception("Invalid Upgrade File!");
                    } finally {
                        IOUtils.closeQuietly(jarInputStream);
                    }
                    // save new .jar file as "ready"
                    fileItem.write(new File("Sketchy.jar.ready"));
                    jsonServletResult.put("version", version);
                }
            }
        }
    } catch (Exception e) {
        jsonServletResult = new JSONServletResult(Status.ERROR, e.getMessage());
    }
    response.setContentType("text/html");
    response.setStatus(HttpServletResponse.SC_OK);
    response.getWriter().print(jsonServletResult.toJSONString());
}

From source file:ar.com.easytech.faces.filters.MultipartRequest.java

@SuppressWarnings("unchecked")
public MultipartRequest(HttpServletRequest request, String path) throws Exception {
    super(request);
    DiskFileItemFactory factory = new DiskFileItemFactory();

    if (path != null)
        factory.setRepository(new File(path));

    ServletFileUpload upload = new ServletFileUpload(factory);
    parameterMap.put("path", path);

    try {/*from ww w  .j  a va  2s .  com*/
        List<FileItem> items = (List<FileItem>) upload.parseRequest(request);

        for (FileItem item : items) {

            String str = item.getString();
            if (item.isFormField())
                parameterMap.put(item.getFieldName(), str);
            else {
                if (item.getName() != null) {
                    parameterMap.put("fileName", item.getName());
                }
                request.setAttribute(item.getFieldName(), item);
            }
        }

    } catch (FileUploadException ex) {
        ServletException servletEx = new ServletException();
        servletEx.initCause(ex);
        throw new Exception(ex.getLocalizedMessage());
    }
}

From source file:br.com.caelum.vraptor.observer.upload.CommonsUploadMultipartObserver.java

protected ServletFileUpload createServletFileUpload(MultipartConfig config) {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository(config.getDirectory());

    logger.debug("Using repository {} for file upload", factory.getRepository());

    return new ServletFileUpload(factory);
}

From source file:com.googlecode.example.FileUploadServlet.java

@Override
@SuppressWarnings({ "unchecked" })
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Processing request...");
    if (isMultipartContent(request)) {
        String storageRoot = request.getSession().getServletContext().getRealPath(STORAGE_ROOT);
        File dirPath = new File(storageRoot);
        if (!dirPath.exists()) {
            if (dirPath.mkdirs()) {
                logger.debug("Storage directories created successfully.");
            }/*w  ww.jav a  2s .  c  om*/
        }
        PrintWriter writer = response.getWriter();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(UPLOAD_SIZE);
        factory.setRepository(dirPath);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(UPLOAD_SIZE);
        try {
            List<FileItem> items = upload.parseRequest(request);
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    File file = new File(new StringBuilder(storageRoot).append("/")
                            .append(getName(item.getName())).toString());
                    logger.debug("Writing file to: {}", file.getCanonicalPath());
                    item.write(file);
                }
            }
            response.setStatus(SC_OK);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            response.setStatus(SC_INTERNAL_SERVER_ERROR);
        }
        writer.flush();
    }
}

From source file:Controller.Publicacion.java

private String uploadFile(HttpServletRequest request) {
    String imageName = "", textfield = "";
    String archivourl = "C:\\xampp\\htdocs\\RedSocial\\web\\files";
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(5000 * 1024);
    factory.setRepository(new File(archivourl));
    ServletFileUpload upload = new ServletFileUpload(factory);

    try {//w  w w .  ja  v  a  2  s.co  m
        List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        String inputName = null;
        for (FileItem item : multiparts) {
            if (!item.isFormField()) {
                String name = new File(item.getName()).getName();
                item.write(new File(archivourl + File.separator + name));
                imageName = name;
            }
            if (item.isFormField()) {
                inputName = (String) item.getFieldName();
                if (inputName.equalsIgnoreCase("cont")) {
                    textfield = (String) item.getString();
                    imageName = textfield;
                }
            }
        }

    } catch (Exception e) {

    }
    return imageName;
}

From source file:br.com.caelum.vraptor.interceptor.multipart.CommonsUploadMultipartInterceptor.java

protected FileItemFactory createFactoryForDiskBasedFileItems(File temporaryDirectory) {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository(temporaryDirectory);

    logger.debug("Using repository {} for file upload", factory.getRepository());
    return factory;
}

From source file:com.sketchy.server.ImageUploadServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    JSONServletResult jsonServletResult = new JSONServletResult(Status.SUCCESS);
    try {//from ww w. j a v  a  2 s . co m

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setRepository(FileUtils.getTempDirectory());
            factory.setSizeThreshold(MAX_SIZE);

            ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
            List<FileItem> files = servletFileUpload.parseRequest(request);
            for (FileItem fileItem : files) {
                String uploadFileName = fileItem.getName();
                if (StringUtils.isNotBlank(uploadFileName)) {
                    // Don't allow \\ in the filename, assume it's a directory separator and convert to "/"
                    // and take the filename after the last "/"
                    // This will fix the issue of Jetty not reading and serving files
                    // with "\" (%5C) characters 
                    // This also fixes the issue of IE sometimes sending the whole path 
                    // (depending on the security settings)
                    uploadFileName = StringUtils.replaceChars(uploadFileName, "\\", "/");
                    if (StringUtils.contains(uploadFileName, "/")) {
                        uploadFileName = StringUtils.substringAfterLast(uploadFileName, "/");
                    }

                    File uploadFile = HttpServer.getUploadFile(uploadFileName);
                    // make sure filename is actually in the upload directory
                    // we don't want any funny games
                    if (!uploadFile.getParentFile().equals(HttpServer.IMAGE_UPLOAD_DIRECTORY)) {
                        throw new RuntimeException("Can not upload File. Invalid directory!");
                    }

                    // if saved ok, then need to add the data file
                    SourceImageAttributes sourceImageAttributes = new SourceImageAttributes();
                    sourceImageAttributes.setImageName(uploadFileName);

                    File pngFile = HttpServer.getUploadFile(sourceImageAttributes.getImageFilename());
                    if (pngFile.exists()) {
                        throw new Exception(
                                "Can not Upload file. File '" + uploadFileName + "' already exists!");
                    }
                    File dataFile = HttpServer.getUploadFile(sourceImageAttributes.getDataFilename());

                    // Convert the image to a .PNG file
                    BufferedImage image = ImageUtils.loadImage(fileItem.getInputStream());
                    ImageUtils.saveImage(pngFile, image);

                    sourceImageAttributes.setWidth(image.getWidth());
                    sourceImageAttributes.setHeight(image.getHeight());

                    FileUtils.writeStringToFile(dataFile, sourceImageAttributes.toJson());
                    jsonServletResult.put("imageName", uploadFileName);
                }
            }
        }
    } catch (Exception e) {
        jsonServletResult = new JSONServletResult(Status.ERROR, e.getMessage());
    }
    response.setContentType("text/html");
    response.setStatus(HttpServletResponse.SC_OK);
    response.getWriter().print(jsonServletResult.toJSONString());
}