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:msec.org.FileUploadServlet.java

static protected String FileUpload(Map<String, String> fields, List<String> filesOnServer,
        HttpServletRequest request, HttpServletResponse response) {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    int MaxMemorySize = 10000000;
    int MaxRequestSize = MaxMemorySize;
    String tmpDir = System.getProperty("TMP", "/tmp");
    //System.out.printf("temporary directory:%s", tmpDir);

    // Set factory constraints
    factory.setSizeThreshold(MaxMemorySize);
    factory.setRepository(new File(tmpDir));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("utf8");

    // Set overall request size constraint
    upload.setSizeMax(MaxRequestSize);/*  w w  w  .  ja  v  a2s.c o  m*/

    // Parse the request
    try {
        @SuppressWarnings("unchecked")
        List<FileItem> items = upload.parseRequest(request);
        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();
            if (item.isFormField()) {//k -v

                String name = item.getFieldName();
                String value = item.getString("utf-8");
                fields.put(name, value);
            } else {

                String fieldName = item.getFieldName();
                String fileName = item.getName();
                if (fileName == null || fileName.length() < 1) {
                    return "file name is empty.";
                }
                String localFileName = ServletConfig.fileServerRootDir + File.separator + "tmp" + File.separator
                        + fileName;
                //System.out.printf("upload file:%s", localFileName);
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                File uploadedFile = new File(localFileName);
                item.write(uploadedFile);
                filesOnServer.add(localFileName);
            }

        }
        return "success";
    } catch (FileUploadException e) {
        e.printStackTrace();
        return e.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return e.toString();
    }

}

From source file:Model.Picture.java

public static ArrayList<String> upload(HttpServletRequest request, int type) {
    ArrayList<String> errors = new ArrayList<String>();
    ArrayList<String> pictureNames = new ArrayList<String>();

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(Constants.UPLOAD_SIZE_THRESHOLD);
    new File(Constants.TEMP_DIR).mkdirs();
    factory.setRepository(new File(Constants.TEMP_DIR));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(Constants.MAX_UPLOAD_SIZE);

    try {// ww w .  j av a 2 s  . co m
        List fileItems = upload.parseRequest(request);
        Iterator i = fileItems.iterator();

        while (i.hasNext()) {
            FileItem fileItem = (FileItem) i.next();
            String fileName = fileItem.getName();

            if (type == EXCEL_UPLOAD)
                errors.addAll(upload_excel(fileName, fileItem));
            else if (type == PICTURE_UPLOAD)
                errors.addAll(upload_picture(fileName, fileItem, pictureNames));
        }
    } catch (org.apache.commons.fileupload.FileUploadException e) {
        e.printStackTrace(System.out);
    } catch (Exception e) {
        e.printStackTrace(System.out);
    }

    if (type == PICTURE_UPLOAD)
        DataBaseTools.insertAndUpdateRecords(pictureNames);

    return errors;
}

From source file:elw.web.ControllerElw.java

private static DiskFileItemFactory createFileItemFactory() {
    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    fileItemFactory.setRepository(new java.io.File(System.getProperty("java.io.tmpdir")));
    fileItemFactory.setSizeThreshold(2 * 1024 * 1024);

    return fileItemFactory;
}

From source file:jeeves.server.sources.JeevletServiceRequestFactory.java

private static Element getMultipartParams(Request req, String uploadDir, int maxUploadSize) throws Exception {

    Element params = new Element("params");

    // FIXME FileUpload - confirm only "multipart/form-data" entities must be parsed here ...
    // if (entity != null && MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {

    // The Apache FileUpload project parses HTTP requests which
    // conform to RFC 1867, "Form-based File Upload in HTML". That
    // is, if an HTTP request is submitted using the POST method,
    // and with a content type of "multipart/form-data", then
    // FileUpload can parse that request, and get all uploaded files
    // as FileItem.

    // 1/ Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1000240); // en mmoire
    factory.setRepository(new File(uploadDir));

    // 2/ Create a new file upload handler based on the Restlet
    // FileUpload extension that will parse Restlet requests and
    // generates FileItems.
    RestletFileUpload upload = new RestletFileUpload(factory);

    upload.setFileSizeMax(maxUploadSize * 1024 * 1024);

    List<FileItem> items;//  www  .  j  a  v a2s  .  c o  m
    try {
        items = upload.parseRequest(req);// parseRepresentation(req.getEntity());

        for (final Iterator<FileItem> it = items.iterator(); it.hasNext();) {
            FileItem item = (FileItem) it.next();

            String name = item.getFieldName();

            if (item.isFormField())
                params.addContent(new Element(name).setText(item.getString()));
            else {
                String file = item.getName();
                String type = item.getContentType();
                long size = item.getSize();
                Log.debug(Log.REQUEST, "Uploading file " + file + " type: " + type + " size: " + size);
                //--- remove path information from file (some browsers put it, like IE)

                file = simplifyName(file);
                Log.debug(Log.REQUEST, "File is called " + file + " after simplification");

                //--- we could get troubles if 2 users upload files with the same name
                item.write(new File(uploadDir, file));

                Element elem = new Element(name).setAttribute("type", "file")
                        .setAttribute("size", Long.toString(size)).setText(file);

                if (type != null)
                    elem.setAttribute("content-type", type);

                Log.debug(Log.REQUEST, "Adding to parameters: " + Xml.getString(elem));
                params.addContent(elem);
            }
        }
    } catch (FileUploadBase.FileSizeLimitExceededException e) {
        // throw jeeves exception --> reached code ? see apache docs -
        // FileUploadBase
        throw new FileUploadTooBigEx();
    } catch (FileUploadException e) {
        // Sample Restlet ... " 

        // The message of all thrown exception is sent back to client as simple plain text
        // response.setEntity(new StringRepresentation(e.getMessage(), MediaType.TEXT_PLAIN));
        // response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        // e.printStackTrace();

        // " ... now throw a JeevletException but
        // FIXME must throw Exception with a correct Status
        throw new JeevletException(e);
    }

    return params;
}

From source file:com.aaasec.sigserv.csspserver.utility.SpServerLogic.java

public static String processFileUpload(HttpServletRequest request, HttpServletResponse response,
        RequestModel req) {//from ww  w .ja  va 2  s  . com
    // Create a factory for disk-based file items
    Map<String, String> paraMap = new HashMap<String, String>();
    File uploadedFile = null;
    boolean uploaded = false;
    DiskFileItemFactory factory = new DiskFileItemFactory();
    String uploadDirName = FileOps.getfileNameString(SpModel.getDataDir(), "uploads");
    FileOps.createDir(uploadDirName);
    File storageDir = new File(uploadDirName);
    factory.setRepository(storageDir);

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString();
                paraMap.put(name, value);
            } else {
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                if (fileName.length() > 0) {
                    String contentType = item.getContentType();
                    boolean isInMemory = item.isInMemory();
                    long sizeInBytes = item.getSize();
                    uploadedFile = new File(storageDir, fileName);
                    try {
                        item.write(uploadedFile);
                        uploaded = true;
                    } catch (Exception ex) {
                        LOG.log(Level.SEVERE, null, ex);
                    }
                }
            }

        }
        if (uploaded) {
            return SpServerLogic.getDocUploadResponse(req, uploadedFile);
        } else {
            if (paraMap.containsKey("xmlName")) {
                return SpServerLogic.getServerDocResponse(req, paraMap.get("xmlName"));
            }
        }
    } catch (FileUploadException ex) {
        LOG.log(Level.SEVERE, null, ex);
    }
    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    return "";
}

From source file:com.fjn.helper.common.io.file.upload.FileUploadHelper.java

/**
 * ?request?fireDir?request.setAttribute(fieldName, value)?
 *
 * @param request /*from w  w  w. j av a  2 s.c o  m*/
 * @param fileDir 
 * @param maxSize ?
 * @param isFileNameBaseTime ????
 * @param encoding
 */
public static FileUploadRequestParamterContext upload(HttpServletRequest request, String fileDir, int maxSize,
        boolean isFileNameBaseTime, String encoding) {
    // ?
    if (!isFileUploadRequest(request))
        return null;
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // dir??
    File dir = new File(fileDir);
    if (!dir.exists()) {
        if (dir.mkdirs()) {
            throw new FileDirFaultException(dir);
        }
        ;
    }
    if (maxSize > 0) {
        factory.setSizeThreshold(maxSize);
    }

    factory.setRepository(dir);

    // ?
    ServletFileUpload fileUploader = new ServletFileUpload(factory);
    fileUploader.setHeaderEncoding(encodingCheck(encoding) ? encoding : defaultEncoding);
    String realEncoding = fileUploader.getHeaderEncoding();

    List<FileItem> items = null;
    try {
        items = fileUploader.parseRequest(request);
    } catch (FileUploadException e1) {
        e1.printStackTrace();
    }
    if (items == null)
        return null;

    FileUploadRequestParamterContext context = new FileUploadRequestParamterContext();
    Map<String, List<File>> fileMap = context.getFileMap();
    Map<String, List<String>> fieldMap = context.getFormFieldMap();

    FileItem fileItem = null;
    Iterator<FileItem> iter = items.iterator();
    while (iter.hasNext()) {
        fileItem = iter.next();
        String fieldName = fileItem.getFieldName();
        if (fileItem.isFormField()) {
            List<String> values = fieldMap.get(fieldName);
            if (values == null) {
                values = new ArrayList<String>();
                fieldMap.put(fieldName, values);
            }
            String value = null;
            try {
                value = fileItem.getString(realEncoding);
            } catch (UnsupportedEncodingException e) {
                value = "";
                e.printStackTrace();
            }
            values.add(value);
            log.info("param:\t" + fieldName + "=" + value);
        } else {
            List<File> files = fileMap.get(fieldName);
            if (files == null) {
                files = new ArrayList<File>();
                fileMap.put(fieldName, files);
            }

            String clientFileName = fileItem.getName();// ???
            if (StringUtil.isNull(clientFileName)) { // 
                continue;
            }
            String realFileName = FileUtil.getRealFileName(clientFileName);
            String newFileName = null;
            if (isFileNameBaseTime) {
                newFileName = new FileNameBuilder().build(realFileName);
            } else {
                newFileName = realFileName;
            }
            File tempfile = new File(dir, newFileName);
            try {
                fileItem.write(tempfile);
                log.info("???\t" + newFileName);
                files.add(tempfile);
            } catch (Exception e) {
                continue;
            }
        }
    }

    return null;
}

From source file:com.easyjf.web.core.FrameworkEngine.java

/**
 * ?requestform//from  w ww . j a  v  a  2s .c o  m
 * 
 * @param request
 * @param formName
 * @return ??Form
 */
public static WebForm creatWebForm(HttpServletRequest request, String formName, Module module) {
    Map textElement = new HashMap();
    Map fileElement = new HashMap();
    String contentType = request.getContentType();
    String reMethod = request.getMethod();
    if ((contentType != null) && (contentType.startsWith("multipart/form-data"))
            && (reMethod.equalsIgnoreCase("post"))) {
        //  multipart/form-data
        File file = new File(request.getSession().getServletContext().getRealPath("/temp"));
        if (!file.exists()) {
            file.getParentFile().mkdirs();
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(webConfig.getUploadSizeThreshold());
        factory.setRepository(file);
        ServletFileUpload sf = new ServletFileUpload(factory);
        sf.setSizeMax(webConfig.getMaxUploadFileSize());
        sf.setHeaderEncoding(request.getCharacterEncoding());
        List reqPars = null;
        try {
            reqPars = sf.parseRequest(request);
            for (int i = 0; i < reqPars.size(); i++) {
                FileItem it = (FileItem) reqPars.get(i);
                if (it.isFormField()) {
                    textElement.put(it.getFieldName(), it.getString(request.getCharacterEncoding()));// ??
                } else {
                    fileElement.put(it.getFieldName(), it);// ???
                }
            }
        } catch (Exception e) {
            logger.error(e);
        }
    } else if ((contentType != null) && contentType.equals("text/xml")) {
        StringBuffer buffer = new StringBuffer();
        try {
            String s = request.getReader().readLine();
            while (s != null) {
                buffer.append(s + "\n");
                s = request.getReader().readLine();
            }
        } catch (Exception e) {
            logger.error(e);
        }
        textElement.put("xml", buffer.toString());
    } else {
        textElement = request2map(request);
    }
    // logger.debug("????");
    WebForm wf = findForm(formName);
    wf.setValidate(module.isValidate());// ?validate?Form
    if (wf != null) {
        wf.setFileElement(fileElement);
        wf.setTextElement(textElement);
    }
    return wf;
}

From source file:com.zlfun.framework.excel.ExcelUtils.java

public static <T> List<T> httpInput(HttpServletRequest request, Class<T> clazz) {
    List<T> result = new ArrayList<T>();
    //??  /*from   w ww.  ja v  a 2s . co m*/
    DiskFileItemFactory factory = new DiskFileItemFactory();
    //??  
    String path = request.getSession().getServletContext().getRealPath("/");
    factory.setRepository(new File(path));
    // ??   
    factory.setSizeThreshold(1024 * 1024);
    ServletFileUpload upload = new ServletFileUpload(factory);

    try {
        //?  
        List<FileItem> list = (List<FileItem>) upload.parseRequest(request);

        for (FileItem item : list) {
            //????  
            String name = item.getFieldName();

            //? ??  ?  
            if (item.isFormField()) {
                //? ??????   
                String value = item.getString();

                request.setAttribute(name, value);
            } //? ??    
            else {
                /**
                 * ?? ??
                 */
                //???  
                String value = item.getName();
                //????  

                fill(clazz, result, value, item.getInputStream());

                //??
            }
        }

    } catch (FileUploadException ex) {
        // TODO Auto-generated catch block      excel=null;
        Logger.getLogger(ExcelUtils.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {

        Logger.getLogger(ExcelUtils.class.getName()).log(Level.SEVERE, null, ex);
    }
    return result;
}

From source file:com.zimbra.cs.service.FileUploadServlet.java

public static ServletFileUpload getUploader(long maxSize) {
    DiskFileItemFactory dfif = new DiskFileItemFactory();
    dfif.setSizeThreshold(32 * 1024);/*from   w ww.  j av  a  2  s  .c o  m*/
    dfif.setRepository(new File(getUploadDir()));
    ServletFileUpload upload = new ServletFileUpload(dfif);
    upload.setSizeMax(maxSize);
    upload.setHeaderEncoding("utf-8");
    return upload;
}

From source file:dk.clarin.tools.userhandle.java

@SuppressWarnings("unchecked")
public static List<FileItem> getParmList(HttpServletRequest request) throws ServletException {
    List<FileItem> items = null;
    boolean is_multipart_formData = ServletFileUpload.isMultipartContent(request);

    if (is_multipart_formData) {
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        /*/* ww  w  . ja v  a 2 s .com*/
        *Set the size threshold, above which content will be stored on disk.
        */
        fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB
        /*
        * Set the temporary directory to store the uploaded files of size above threshold.
        */
        File tmpDir = new File(ToolsProperties.tempdir);
        if (!tmpDir.isDirectory()) {
            throw new ServletException("Trying to set \"" + ToolsProperties.tempdir
                    + "\" as temporary directory, but this is not a valid directory.");
        }
        fileItemFactory.setRepository(tmpDir);

        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
        try {
            items = (List<FileItem>) uploadHandler.parseRequest(request);
        } catch (FileUploadException ex) {
            logger.error("Error encountered while parsing the request: " + ex.getMessage());
        }
    }
    return items;
}