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:com.insurance.manage.UploadFile.java

private void uploadLicense(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //      boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    //       Create a factory for disk-based file items
    String custId = null;//from  w  ww.j  a  v  a  2s. c  o m
    String year = null;
    String license = null;
    CustomerManager cManage = new CustomerManager();
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1 * 1024 * 1024); //1 MB
    factory.setRepository(new File("temp"));

    //       Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    HttpSession session = request.getSession();
    //      System.out.println("eCust : "+session.getAttribute("eCust"));
    //      if (session.getAttribute("eCust")!=null) {
    //         Customer cEntity = (Customer)request.getAttribute("eCust");
    //         System.out.println("CustId : "+cEntity.getName());
    //      }

    //       Parse the request
    //      System.out.println("--------- Uploading --------------");
    try {
        List /* FileItem */ items = upload.parseRequest(request);
        //          Process the uploaded items
        Iterator iter = items.iterator();
        File fi = null;
        File file = null;
        Calendar calendar = Calendar.getInstance();
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = df.format(calendar.getTime()) + ".jpg";
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                //                System.out.println(item.getFieldName()+" : "+item.getName()+" : "+item.getString()+" : "+item.getContentType());
                if (item.getFieldName().equals("custId") && !item.getString().equals("")) {
                    custId = item.getString();
                    //                   System.out.println("custId : "+custId);
                }
                if (item.getFieldName().equals("year") && !item.getString().equals("")) {
                    year = item.getString();
                    //                   System.out.println("year : "+year);
                }
                if (item.getFieldName().equals("license") && !item.getString().equals("")) {
                    license = (String) session.getAttribute(item.getString());
                    //                   System.out.println("license : "+license+" : "+session.getAttribute(item.getString()));
                }
            } else {
                //                Handle Uploaded files.
                //                System.out.println("Handle Uploaded files.");
                if (item.getFieldName().equals("vat") && !item.getName().equals("")) {
                    fi = new File(item.getName());
                    File uploadedFile = new File(
                            getServletContext().getRealPath("/images/license/vat/" + year + fileName));
                    item.write(uploadedFile);
                    cManage.updatePicture(custId, year, license, "vatpic", year + fileName);
                }
                if (item.getFieldName().equals("car") && !item.getName().equals("")) {
                    fi = new File(item.getName());
                    File uploadedFile = new File(
                            getServletContext().getRealPath("/images/license/car/" + year + fileName));
                    item.write(uploadedFile);
                    cManage.updatePicture(custId, year, license, "carpic", year + fileName);
                }
                if (item.getFieldName().equals("act") && !item.getName().equals("")) {
                    fi = new File(item.getName());
                    File uploadedFile = new File(
                            getServletContext().getRealPath("/images/license/act/" + year + fileName));
                    item.write(uploadedFile);
                    cManage.updatePicture(custId, year, license, "actpic", year + fileName);
                }
                if (item.getFieldName().equals("chk") && !item.getName().equals("")) {
                    fi = new File(item.getName());
                    File uploadedFile = new File(
                            getServletContext().getRealPath("/images/license/chk/" + year + fileName));
                    item.write(uploadedFile);
                    cManage.updatePicture(custId, year, license, "chkpic", year + fileName);
                }
            }
        }
    } catch (FileUploadException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    request.setAttribute("url", "setup/CustomerMultiMT.jsp?action=search&custId=" + custId);
    request.setAttribute("msg", "!!!Uploading !!!");
    getServletConfig().getServletContext().getRequestDispatcher("/Reload.jsp").forward(request, response);

}

From source file:com.liferay.faces.metal.component.inputfile.internal.InputFileDecoderCommonsImpl.java

@Override
public Map<String, List<UploadedFile>> decode(FacesContext facesContext, String location) {

    Map<String, List<UploadedFile>> uploadedFileMap = null;
    ExternalContext externalContext = facesContext.getExternalContext();
    String uploadedFilesFolder = getUploadedFilesFolder(externalContext, location);

    // Using the sessionId, determine a unique folder path and create the path if it does not exist.
    String sessionId = getSessionId(externalContext);

    // FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be
    // created properly.
    sessionId = sessionId.replaceAll("[^A-Za-z0-9]", " ");

    File uploadedFilesPath = new File(uploadedFilesFolder, sessionId);

    if (!uploadedFilesPath.exists()) {
        uploadedFilesPath.mkdirs();//w  w w.  j  ava2 s  .c o m
    }

    // Initialize commons-fileupload with the file upload path.
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    diskFileItemFactory.setRepository(uploadedFilesPath);

    // Initialize commons-fileupload so that uploaded temporary files are not automatically deleted.
    diskFileItemFactory.setFileCleaningTracker(null);

    // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk
    // instead of staying in memory.
    diskFileItemFactory.setSizeThreshold(0);

    // Determine the max file upload size threshold (in bytes).
    int uploadedFileMaxSize = WebConfigParam.UploadedFileMaxSize.getIntegerValue(externalContext);

    // Parse the request parameters and save all uploaded files in a map.
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    servletFileUpload.setFileSizeMax(uploadedFileMaxSize);
    uploadedFileMap = new HashMap<String, List<UploadedFile>>();

    UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) FactoryExtensionFinder
            .getFactory(UploadedFileFactory.class);

    // Begin parsing the request for file parts:
    try {
        FileItemIterator fileItemIterator = null;

        HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest();
        fileItemIterator = servletFileUpload.getItemIterator(httpServletRequest);

        if (fileItemIterator != null) {

            int totalFiles = 0;

            // For each field found in the request:
            while (fileItemIterator.hasNext()) {

                try {
                    totalFiles++;

                    // Get the stream of field data from the request.
                    FileItemStream fieldStream = (FileItemStream) fileItemIterator.next();

                    // Get field name from the field stream.
                    String fieldName = fieldStream.getFieldName();

                    // Get the content-type, and file-name from the field stream.
                    String contentType = fieldStream.getContentType();
                    boolean formField = fieldStream.isFormField();

                    String fileName = null;

                    try {
                        fileName = fieldStream.getName();
                    } catch (InvalidFileNameException e) {
                        fileName = e.getName();
                    }

                    // Copy the stream of file data to a temporary file. NOTE: This is necessary even if the
                    // current field is a simple form-field because the call below to diskFileItem.getString()
                    // will fail otherwise.
                    DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName,
                            contentType, formField, fileName);
                    Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true);

                    // If the current field is a file, then
                    if (!diskFileItem.isFormField()) {

                        // Get the location of the temporary file that was copied from the request.
                        File tempFile = diskFileItem.getStoreLocation();

                        // If the copy was successful, then
                        if (tempFile.exists()) {

                            // Copy the commons-fileupload temporary file to a file in the same temporary
                            // location, but with the filename provided by the user in the upload. This has two
                            // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying
                            // the file, the developer can have access to a semi-permanent file, because the
                            // commmons-fileupload DiskFileItem.finalize() method automatically deletes the
                            // temporary one.
                            String tempFileName = tempFile.getName();
                            String tempFileAbsolutePath = tempFile.getAbsolutePath();

                            String copiedFileName = stripIllegalCharacters(fileName);

                            String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName,
                                    copiedFileName);
                            File copiedFile = new File(copiedFileAbsolutePath);
                            FileUtils.copyFile(tempFile, copiedFile);

                            // If present, build up a map of headers.
                            Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
                            FileItemHeaders fileItemHeaders = fieldStream.getHeaders();

                            if (fileItemHeaders != null) {
                                Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames();

                                if (headerNameItr != null) {

                                    while (headerNameItr.hasNext()) {
                                        String headerName = headerNameItr.next();
                                        Iterator<String> headerValuesItr = fileItemHeaders
                                                .getHeaders(headerName);
                                        List<String> headerValues = new ArrayList<String>();

                                        if (headerValuesItr != null) {

                                            while (headerValuesItr.hasNext()) {
                                                String headerValue = headerValuesItr.next();
                                                headerValues.add(headerValue);
                                            }
                                        }

                                        headersMap.put(headerName, headerValues);
                                    }
                                }
                            }

                            // Put a valid UploadedFile instance into the map that contains all of the
                            // uploaded file's attributes, along with a successful status.
                            Map<String, Object> attributeMap = new HashMap<String, Object>();
                            String id = Long.toString(((long) hashCode()) + System.currentTimeMillis());
                            String message = null;
                            UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(
                                    copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(),
                                    diskFileItem.getContentType(), headersMap, id, message, fileName,
                                    diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED);

                            addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName,
                                    fileName);
                        } else {

                            if ((fileName != null) && (fileName.trim().length() > 0)) {
                                Exception e = new IOException("Failed to copy the stream of uploaded file=["
                                        + fileName
                                        + "] to a temporary file (possibly a zero-length uploaded file)");
                                UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                                addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(e);

                    UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                    String fieldName = Integer.toString(totalFiles);
                    addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                }
            }
        }
    }

    // If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in
    // the map so that the developer can have some idea that something went wrong.
    catch (Exception e) {
        logger.error(e);

        UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
        addUploadedFile(uploadedFileMap, "unknown", uploadedFile);
    }

    return uploadedFileMap;
}

From source file:emsa.webcoc.cleanup.servlet.UploadServet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w w  w .ja v a  2  s .co m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    if (!isMultipart) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>XML file clean up</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
        return;
    }

    DiskFileItemFactory factory = new DiskFileItemFactory();

    //Maximum size that will be stored into memory
    factory.setSizeThreshold(MAXMEMSIZE);
    //Path to save file if its size is bigger than MAXMEMSIZE
    factory.setRepository(new File(REPOSITORY));
    ServletFileUpload upload = new ServletFileUpload(factory);

    out.println("<html>");
    out.println("<head>");
    out.println("<title>XML file clean up</title>");
    out.println("</head>");
    out.println("<body>");

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

        while (t.hasNext()) {
            FileItem f = t.next();

            if (!f.isFormField()) {
                if (f.getContentType().equals("text/xml")) { //Check weather or not the uploaded file is an XML file

                    String uniqueFileName = f.getName() + "-" + request.getSession().getId() + ".xml"; //Creates unique name
                    String location = (String) this.getServletContext().getAttribute("newFileLocation");

                    CoCCleanUp clean = new CoCCleanUp(uniqueFileName, location);

                    if (clean.cleanDocument(f.getInputStream()) == 0) {
                        out.println("<h3>" + f.getName() + " was clean</h3>");
                        out.println(clean.printHTMLStatistics());
                        out.println("<br /><form action='download?filename=" + uniqueFileName
                                + "' method='post'><input type='submit' value='Download'/></form></body></html>");
                    } else {
                        out.println("<h3>" + clean.getErrorMessage() + "</h3>");
                        out.println(
                                "<br /><form action='index.html' method='post'><input type='submit' value='Go Back'/></form></body></html>");
                    }
                } else {
                    out.println("<h3>The file " + f.getName() + " is not an xml file</h3>");
                    out.println(
                            "<br /><form action='index.html' method='post'><input type='submit' value='Go Back'/></form></body></html>");
                    logger.warn("The file " + f.getName() + " is not an xml file: " + f.getContentType());
                }
            }
        }

        File repository = factory.getRepository();
        cleanTmpFiles(repository);

    } catch (IOException | FileUploadException e) {
        out.println("<h3>Something went wrong</h3></br>");
        out.println(
                "<br /><form action='index.html' method='post'><input type='submit' value='Go Back'/></form></body></html>");
    }
}

From source file:com.liferay.faces.alloy.component.inputfile.internal.InputFileDecoderCommonsImpl.java

@Override
public Map<String, List<UploadedFile>> decode(FacesContext facesContext, String location) {

    Map<String, List<UploadedFile>> uploadedFileMap = null;
    ExternalContext externalContext = facesContext.getExternalContext();
    String uploadedFilesFolder = getUploadedFilesFolder(externalContext, location);

    // Using the sessionId, determine a unique folder path and create the path if it does not exist.
    String sessionId = getSessionId(externalContext);

    // FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be
    // created properly.
    sessionId = sessionId.replaceAll("[^A-Za-z0-9]", " ");

    File uploadedFilesPath = new File(uploadedFilesFolder, sessionId);

    if (!uploadedFilesPath.exists()) {
        uploadedFilesPath.mkdirs();//from   w w  w .j a  v a2s  .  c  o  m
    }

    // Initialize commons-fileupload with the file upload path.
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    diskFileItemFactory.setRepository(uploadedFilesPath);

    // Initialize commons-fileupload so that uploaded temporary files are not automatically deleted.
    diskFileItemFactory.setFileCleaningTracker(null);

    // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk
    // instead of staying in memory.
    diskFileItemFactory.setSizeThreshold(0);

    // Determine the max file upload size threshold (in bytes).
    int uploadedFileMaxSize = WebConfigParam.UploadedFileMaxSize.getIntegerValue(externalContext);

    // Parse the request parameters and save all uploaded files in a map.
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    servletFileUpload.setFileSizeMax(uploadedFileMaxSize);
    uploadedFileMap = new HashMap<String, List<UploadedFile>>();

    UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) FactoryExtensionFinder
            .getFactory(externalContext, UploadedFileFactory.class);

    // Begin parsing the request for file parts:
    try {
        FileItemIterator fileItemIterator = null;

        HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest();
        fileItemIterator = servletFileUpload.getItemIterator(httpServletRequest);

        if (fileItemIterator != null) {

            int totalFiles = 0;

            // For each field found in the request:
            while (fileItemIterator.hasNext()) {

                try {
                    totalFiles++;

                    // Get the stream of field data from the request.
                    FileItemStream fieldStream = (FileItemStream) fileItemIterator.next();

                    // Get field name from the field stream.
                    String fieldName = fieldStream.getFieldName();

                    // Get the content-type, and file-name from the field stream.
                    String contentType = fieldStream.getContentType();
                    boolean formField = fieldStream.isFormField();

                    String fileName = null;

                    try {
                        fileName = fieldStream.getName();
                    } catch (InvalidFileNameException e) {
                        fileName = e.getName();
                    }

                    // Copy the stream of file data to a temporary file. NOTE: This is necessary even if the
                    // current field is a simple form-field because the call below to diskFileItem.getString()
                    // will fail otherwise.
                    DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName,
                            contentType, formField, fileName);
                    Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true);

                    // If the current field is a file, then
                    if (!diskFileItem.isFormField()) {

                        // Get the location of the temporary file that was copied from the request.
                        File tempFile = diskFileItem.getStoreLocation();

                        // If the copy was successful, then
                        if (tempFile.exists()) {

                            // Copy the commons-fileupload temporary file to a file in the same temporary
                            // location, but with the filename provided by the user in the upload. This has two
                            // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying
                            // the file, the developer can have access to a semi-permanent file, because the
                            // commmons-fileupload DiskFileItem.finalize() method automatically deletes the
                            // temporary one.
                            String tempFileName = tempFile.getName();
                            String tempFileAbsolutePath = tempFile.getAbsolutePath();

                            String copiedFileName = stripIllegalCharacters(fileName);

                            String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName,
                                    copiedFileName);
                            File copiedFile = new File(copiedFileAbsolutePath);
                            FileUtils.copyFile(tempFile, copiedFile);

                            // If present, build up a map of headers.
                            Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
                            FileItemHeaders fileItemHeaders = fieldStream.getHeaders();

                            if (fileItemHeaders != null) {
                                Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames();

                                if (headerNameItr != null) {

                                    while (headerNameItr.hasNext()) {
                                        String headerName = headerNameItr.next();
                                        Iterator<String> headerValuesItr = fileItemHeaders
                                                .getHeaders(headerName);
                                        List<String> headerValues = new ArrayList<String>();

                                        if (headerValuesItr != null) {

                                            while (headerValuesItr.hasNext()) {
                                                String headerValue = headerValuesItr.next();
                                                headerValues.add(headerValue);
                                            }
                                        }

                                        headersMap.put(headerName, headerValues);
                                    }
                                }
                            }

                            // Put a valid UploadedFile instance into the map that contains all of the
                            // uploaded file's attributes, along with a successful status.
                            Map<String, Object> attributeMap = new HashMap<String, Object>();
                            String id = Long.toString(((long) hashCode()) + System.currentTimeMillis());
                            String message = null;
                            UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(
                                    copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(),
                                    diskFileItem.getContentType(), headersMap, id, message, fileName,
                                    diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED);

                            addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName,
                                    fileName);
                        } else {

                            if ((fileName != null) && (fileName.trim().length() > 0)) {
                                Exception e = new IOException("Failed to copy the stream of uploaded file=["
                                        + fileName
                                        + "] to a temporary file (possibly a zero-length uploaded file)");
                                UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                                addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(e);

                    UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                    String fieldName = Integer.toString(totalFiles);
                    addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                }
            }
        }
    }

    // If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in
    // the map so that the developer can have some idea that something went wrong.
    catch (Exception e) {
        logger.error(e);

        UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
        addUploadedFile(uploadedFileMap, "unknown", uploadedFile);
    }

    return uploadedFileMap;
}

From source file:com.osbitools.ws.shared.prj.web.AbstractWsPrjInit.java

@Override
public void contextInitialized(ServletContextEvent evt) {
    super.contextInitialized(evt);
    ServletContext ctx = evt.getServletContext();

    // First - Load Custom Error List 
    try {/*from w  w  w . j  a v a2 s. c o  m*/
        Class.forName("com.osbitools.ws.shared.prj.CustErrorList");
    } catch (ClassNotFoundException e) {
        // Ignore Error 
    }

    // Initialize Entity Utils
    IEntityUtils eut = getEntityUtils();
    ctx.setAttribute("entity_utils", eut);

    // Initiate LangSetFileUtils
    ctx.setAttribute("ll_set_utils", new LangSetUtils());

    // Check if git repository exists and create one
    // Using ds subdirectory as git root repository 
    File drepo = new File(
            getConfigDir(ctx) + File.separator + eut.getPrjRootDirName() + File.separator + ".git");
    Git git;
    try {

        if (!drepo.exists()) {
            if (!drepo.mkdirs())
                throw new RuntimeErrorException(
                        new Error("Unable create directory '" + drepo.getAbsolutePath() + "'"));

            try {
                git = createGitRepo(drepo);
            } catch (Exception e) {
                throw new RuntimeErrorException(new Error(
                        "Unable create new repo on path: " + drepo.getAbsolutePath() + ". " + e.getMessage()));
            }

            getLogger(ctx).info("Created new git repository '" + drepo.getAbsolutePath() + "'");
        } else if (!drepo.isDirectory()) {
            throw new RuntimeErrorException(
                    new Error(drepo.getAbsolutePath() + " is regular file and not a directory"));
        } else {
            git = Git.open(drepo);
            getLogger(ctx).debug("Open existing repository " + drepo.getAbsolutePath());
        }
    } catch (IOException e) {
        // Something unexpected and needs to be analyzed
        e.printStackTrace();

        throw new RuntimeErrorException(new Error(e));
    }

    // Save git handler
    ctx.setAttribute("git", git);

    // Check if remote destination set/changed
    StoredConfig config = git.getRepository().getConfig();
    String rname = (String) ctx.getAttribute(PrjMgrConstants.PREMOTE_GIT_NAME);
    String rurl = (String) ctx.getAttribute("git_remote_url");

    if (!Utils.isEmpty(rname) && !Utils.isEmpty(rurl)) {
        String url = config.getString("remote", rname, "url");
        if (!rurl.equals(url)) {
            config.setString("remote", rname, "url", rurl);
            try {
                config.save();
            } catch (IOException e) {
                getLogger(ctx).error("Error saving git remote url. " + e.getMessage());
            }
        }
    }

    // Temp directory for files upload
    String tname = System.getProperty("java.io.tmpdir");
    getLogger(ctx).info("Using temporarily directory '" + tname + "' for file uploads");
    File tdir = new File(tname);

    if (!tdir.exists())
        throw new RuntimeErrorException(
                new Error("Temporarily directory for file upload '" + tname + "' is not found"));
    if (!tdir.isDirectory())
        throw new RuntimeErrorException(
                new Error("Temporarily directory for file upload '" + tname + "' is not a directory"));

    DiskFileItemFactory dfi = new DiskFileItemFactory();
    dfi.setSizeThreshold(
            ((Integer) ctx.getAttribute(PrjMgrConstants.SMAX_FILE_UPLOAD_SIZE_NAME)) * 1024 * 1024);
    dfi.setRepository(tdir);
    evt.getServletContext().setAttribute("dfi", dfi);

    // Save entity utils in context
    evt.getServletContext().setAttribute("entity_utils", getEntityUtils());
}

From source file:cn.trymore.core.web.servlet.FileUploadServlet.java

@Override
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");

    try {/* w  w w .  j  av  a  2  s. c  om*/
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        diskFileItemFactory.setSizeThreshold(4096);
        diskFileItemFactory.setRepository(new File(this.tempPath));

        String fileIds = "";

        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        List<FileItem> fileList = (List<FileItem>) servletFileUpload.parseRequest(request);
        Iterator<FileItem> itor = fileList.iterator();
        Iterator<FileItem> itor1 = fileList.iterator();
        String file_type = "";
        while (itor1.hasNext()) {
            FileItem item = itor1.next();
            if (item.isFormField() && "file_type".equals(item.getFieldName())) {
                file_type = item.getString();
            }
        }
        FileItem fileItem;
        while (itor.hasNext()) {
            fileItem = itor.next();

            if (fileItem.getContentType() == null) {
                continue;
            }

            // obtains the file path and name
            String filePath = fileItem.getName();

            String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
            // generates new file name with the current time stamp.
            String newFileName = this.fileCat + "/" + UtilFile.generateFilename(fileName);
            // ensure the directory existed before creating the file.
            File dir = new File(
                    this.uploadPath + "/" + newFileName.substring(0, newFileName.lastIndexOf("/") + 1));
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // stream writes to the destination file
            fileItem.write(new File(this.uploadPath + "/" + newFileName));

            ModelFileAttach fileAttach = null;
            if (request.getParameter("noattach") == null) {
                // storages the file into database.
                fileAttach = new ModelFileAttach();
                fileAttach.setFileName(fileName);
                fileAttach.setFilePath(newFileName);
                fileAttach.setTotalBytes(Long.valueOf(fileItem.getSize()));
                fileAttach.setNote(this.getStrFileSize(fileItem.getSize()));
                fileAttach.setFileExt(fileName.substring(fileName.lastIndexOf(".") + 1));
                fileAttach.setCreatetime(new Date());
                fileAttach.setDelFlag(ModelFileAttach.FLAG_NOT_DEL);
                fileAttach.setFileType(!"".equals(file_type) ? file_type : this.fileCat);

                ModelAppUser user = ContextUtil.getCurrentUser();
                if (user != null) {
                    fileAttach.setCreatorId(Long.valueOf(user.getId()));
                    fileAttach.setCreator(user.getFullName());
                } else {
                    fileAttach.setCreator("Unknow");
                }

                this.serviceFileAttach.save(fileAttach);
            }

            //add by Tang ??fileIds?????
            if (fileAttach != null) {
                fileIds = (String) request.getSession().getAttribute("fileIds");
                if (fileIds == null) {
                    fileIds = fileAttach.getId();
                } else {
                    fileIds = fileIds + "," + fileAttach.getId();
                }
            }
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.println(
                    "{\"status\": 1, \"data\":{\"id\":" + (fileAttach != null ? fileAttach.getId() : "\"\"")
                            + ", \"url\":\"" + newFileName + "\"}}");
        }
        request.getSession().setAttribute("fileIds", fileIds);
    } catch (Exception e) {
        e.printStackTrace();
        response.getWriter().write("{\"status\":0, \"message\":\":" + e.getMessage() + "\"");
    }
}

From source file:com.raissi.utils.CustomFileUploadFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    if (bypass) {
        filterChain.doFilter(request, response);
        return;/*  ww w  . ja  v a2  s . com*/
    }

    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    boolean isMultipart = ServletFileUpload.isMultipartContent(httpServletRequest);

    if (isMultipart) {
        logger.debug("Parsing file upload request");

        FileCleaningTracker fileCleaningTracker = FileCleanerCleanup
                .getFileCleaningTracker(request.getServletContext());
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        diskFileItemFactory.setFileCleaningTracker(fileCleaningTracker);
        if (thresholdSize != null) {
            diskFileItemFactory.setSizeThreshold(Integer.valueOf(thresholdSize));
        }
        if (uploadDir != null) {
            diskFileItemFactory.setRepository(new File(uploadDir));
        }

        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        MultipartRequest multipartRequest = new MultipartRequest(httpServletRequest, servletFileUpload);

        logger.debug(
                "File upload request parsed succesfully, continuing with filter chain with a wrapped multipart request");

        filterChain.doFilter(multipartRequest, response);
    } else {
        filterChain.doFilter(request, response);
    }
}

From source file:com.controller.RecipeImage.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w  ww  . j  av  a  2 s .  c  o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    //retrieving the path to store image from web.xml
    filePath = getServletContext().getInitParameter("recipeImageStorePath");

    //retrieving the path to display image from web.xml
    fileDisplay = getServletContext().getInitParameter("recipeImageDisplayPath");

    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    if (!isMultipart) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
        return;
    }
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File("c:\\temp"));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);

        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("1");
        while (i.hasNext()) {
            out.println("2");
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                fileName = fi.getName();
                fileName = randomString(fileName);
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                } else {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                }
                fi.write(file);
                out.println("Uploaded Filename: " + fileName + "<br>" + filePath);
            } else {
                out.println("No file");
            }
        }
        out.println("</body>");
        out.println("</html>");

        RecipeBean recipeBean = new RecipeBean();
        RecipeDAO recipeDAO = new RecipeDAO();

        String image = fileDisplay + "" + fileName;
        out.println(image);

        HttpSession session = request.getSession();
        String recipeId = (String) session.getAttribute("recipeId");
        session.removeAttribute("recipeId");
        recipeDAO.addImage(recipeId, image);

        response.sendRedirect("Home");

    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:com.food.adminservlet.FoodServlet.java

@Override

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    int foodid = 0;
    String foodName = "";
    String fooddesc = "";
    Double foodprice = 0.0;// w ww  .j  av a2 s .c  o m
    String foodCategory = "";
    PrintWriter out = response.getWriter();
    isMultipart = ServletFileUpload.isMultipartContent(request);
    FoodBean bkfood = new FoodBean();
    FoodBL foodbl = new FoodBL();
    try {

        response.setContentType("text/html");
        //java.io.PrintWriter out = response.getWriter( );

        DiskFileItemFactory factory = new DiskFileItemFactory();
        // maximum size that will be stored in memory
        factory.setSizeThreshold(maxMemSize);
        // Location to save data that is larger than maxMemSize.
        factory.setRepository(new File("c:\\temp"));

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum file size to be uploaded.
        upload.setSizeMax(maxFileSize);

        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);

        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        while (i.hasNext()) {

            FileItem fi = (FileItem) i.next();
            if (fi.isFormField()) {
                if (fi.getFieldName().equals("foodid")) {
                    foodid = Integer.parseInt(fi.getString());
                }
                if (fi.getFieldName().equals("foodname")) {
                    foodName = fi.getString();
                }
                if (fi.getFieldName().equals("fooddesc")) {
                    fooddesc = fi.getString();
                }
                if (fi.getFieldName().equals("foodprice")) {
                    foodprice = Double.parseDouble(fi.getString());
                }
                if (fi.getFieldName().equals("foodcate")) {
                    foodCategory = fi.getString();
                }

                out.println("<br>");
            }
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                } else {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                }
                fi.write(file);
                out.println("Uploaded Filename: " + fileName + "<br>");
            }
        }

        out.println(fileName);

        bkfood.setFoodId(foodid);
        bkfood.setFoodName(foodName);
        bkfood.setFoodPrice(foodprice);
        bkfood.setFoodCateg(foodCategory);
        bkfood.setFoodDesc(fooddesc);
        bkfood.setFoodRetreiveImage(fileName);
        // bkfood.setFoodimage(request.getPart("foodimage"));
        bkfood.setFoodstatus("Y");

        int chk = foodbl.addFoodItems(bkfood);
        out.println(chk);

        if (chk == 1) {
            response.sendRedirect("food.jsp");
        }

    } catch (Exception ex) {
        out.println(ex);
    }
}

From source file:Control.LoadImage.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   w w w . j  a  v a  2  s.c  o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String tempPath = "/temp";
    String absoluteTempPath = this.getServletContext().getRealPath(tempPath);
    String absoluteFilePath = this.getServletContext().getRealPath("/data/Image");
    int maxFileSize = 50 * 1024;
    int maxMemSize = 4 * 1024;

    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(maxMemSize);
        File file = new File(absoluteTempPath);

        if (file == null) {
            // tao thu muc
        }

        factory.setRepository(file);
        ServletFileUpload upload = new ServletFileUpload(factory);

        //upload.setProgressListener(new MyProgressListener(out));
        List<FileItem> items = upload.parseRequest(request);

        if (items.size() > 0) {
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    if ("images".equals(item.getFieldName())) {
                        if (item.getName() != null && !item.getName().isEmpty()) {
                            String extension = null;
                            if (item.getName().endsWith("jpg")) {
                                String newLink = "/Image/" + Image.LengthListImg() + ".jpg";
                                file = new File(absoluteFilePath + "//" + Image.LengthListImg() + ".jpg");
                                // G?i hm add hnh vo database, link hnh l newLink
                                item.write(file);
                            } else if (item.getName().endsWith("png")) {
                                String newLink = "/Image/" + Image.LengthListImg() + ".png";
                                file = new File(absoluteFilePath + "//" + Image.LengthListImg() + ".png");
                                // G?i hm add hnh vo database, link hnh l newLink
                                item.write(file);
                            } else if (item.getName().endsWith("JPG")) {
                                String newLink = "/Image/" + Image.LengthListImg() + ".JPG";
                                file = new File(absoluteFilePath + "//" + Image.LengthListImg() + ".JPG");
                                // G?i hm add hnh vo database, link hnh l newLink
                                item.write(file);
                            } else if (item.getName().endsWith("PNG")) {
                                String newLink = "/Image/" + Image.LengthListImg() + ".PNG";
                                file = new File(absoluteFilePath + "//" + Image.LengthListImg() + ".PNG");
                                // G?i hm add hnh vo database, link hnh l newLink
                                item.write(file);
                            }
                        }
                    }
                } else {
                }
            }
            response.sendRedirect(request.getContextPath() + "/LoadImage.jsp");
            return;
        }

        List<Image> images = loadImages(request, response);

        request.setAttribute("images", images);
        request.setAttribute("error", "No file upload");
        RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/LoadImage.jsp");
        dispatcher.forward(request, response);
    } catch (Exception ex) {
        System.err.println(ex);
    }
}