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() 

Source Link

Document

Constructs an unconfigured instance of this class.

Usage

From source file:it.univaq.servlet.Upload_rist.java

protected boolean action_upload(HttpServletRequest request) throws FileUploadException, Exception {

    HttpSession s = SecurityLayer.checkSession(request);
    //dichiaro mappe 
    Map rist = new HashMap();
    //prendo id pubblicazione dalla request

    if (ServletFileUpload.isMultipartContent(request)) {
        Map files = new HashMap();
        int idpubb = Integer.parseInt(request.getParameter("id"));
        //La dimensione massima di ogni singolo file su system
        int dimensioneMassimaDelFileScrivibieSulFileSystemInByte = 10 * 1024 * 1024; // 10 MB
        //Dimensione massima della request
        int dimensioneMassimaDellaRequestInByte = 20 * 1024 * 1024; // 20 MB

        // Creo un factory per l'accesso al filesystem
        DiskFileItemFactory factory = new DiskFileItemFactory();

        //Setto la dimensione massima di ogni file, opzionale
        factory.setSizeThreshold(dimensioneMassimaDelFileScrivibieSulFileSystemInByte);

        // Istanzio la classe per l'upload
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Setto la dimensione massima della request
        upload.setSizeMax(dimensioneMassimaDellaRequestInByte);

        // Parso la riquest della servlet, mi viene ritornata una lista di FileItem con
        // tutti i field sia di tipo file che gli altri
        List<FileItem> items = upload.parseRequest(request);

        /*/*w  ww . j av a  2s .  c o  m*/
        * La classe usata non permette di riprendere i singoli campi per
        * nome quindi dovremmo scorrere la lista che ci viene ritornata con
        * il metodo parserequest
        */
        //scorro per tutti i campi inviati
        for (int i = 0; i < items.size(); i++) {
            FileItem item = items.get(i);
            // Controllo se si tratta di un campo di input normale
            if (item.isFormField()) {
                // Prendo solo il nome e il valore
                String name = item.getFieldName();
                String value = item.getString();

                if (name.equals("isbn") || name.equals("editore") || name.equals("lingua")
                        || name.equals("numpagine") || name.equals("datapub")) {
                    rist.put(name, value);
                }

            } // Se si stratta invece di un file
            else {
                // Dopo aver ripreso tutti i dati disponibili name,type,size
                //String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                long sizeInBytes = item.getSize();
                //li salvo nella mappa
                files.put("name", fileName);
                files.put("type", contentType);
                files.put("size", sizeInBytes);
                //li scrivo nel db
                //Database.connect();
                Database.insertRecord("files", files);
                //Database.close();

                // Posso scriverlo direttamente su filesystem
                if (true) {
                    File uploadedFile = new File(
                            getServletContext().getInitParameter("uploads.directory") + fileName);
                    // Solo se veramente ho inviato qualcosa
                    if (item.getSize() > 0) {
                        item.write(uploadedFile);
                    }
                }
                //prendo id del file se  stato inserito
                ResultSet rs1 = Database.selectRecord("files", "name='" + files.get("name") + "'");
                if (!isNull(rs1)) {
                    while (rs1.next()) {
                        rist.put("download", rs1.getInt("id"));
                    }
                }

            }

        }

        rist.put("idpub", idpubb);
        //inserisco dati in tab ristampa
        Database.insertRecord("ristampa", rist);

        return true;
    } else
        return false;
}

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

/**
 * ?requestform/*  w  w  w .  ja va 2 s.co 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:edu.fullerton.ldvservlet.Upload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request//from  w  w w  . j a  va2  s. com
 * @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 {
    long startTime = System.currentTimeMillis();

    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("This action requires a multipart form with a file attached.");
    }
    ServletSupport servletSupport;

    servletSupport = new ServletSupport();
    servletSupport.init(request, viewerConfig, false);

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Configure a repository (to ensure a secure temp location is used)
    ServletContext servletContext = this.getServletConfig().getServletContext();
    File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    factory.setRepository(repository);

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    ImageTable imageTable;
    String viewServletPath = request.getContextPath() + "/view";

    try {
        imageTable = new ImageTable(servletSupport.getDb());
    } catch (SQLException ex) {
        String ermsg = "Image upload: can't access the Image table: " + ex.getClass().getSimpleName() + " "
                + ex.getLocalizedMessage();
        throw new ServletException(ermsg);
    }
    try {
        HashMap<String, String> params = new HashMap<>();
        ArrayList<Integer> uploadedIds = new ArrayList<>();

        Page vpage = servletSupport.getVpage();
        vpage.setTitle("Image upload");
        try {
            servletSupport.addStandardHeader(version);
            servletSupport.addNavBar();
        } catch (WebUtilException ex) {
            throw new ServerException("Adding nav bar after upload", ex);
        }

        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        int cnt = items.size();
        for (FileItem item : items) {
            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString();
                if (!value.isEmpty()) {
                    params.put(name, value);
                }
            }
        }
        for (FileItem item : items) {
            if (!item.isFormField()) {
                int imgId = addFile(item, params, vpage, servletSupport.getVuser().getCn(), imageTable);
                if (imgId != 0) {
                    uploadedIds.add(imgId);
                }
            }
        }
        if (!uploadedIds.isEmpty()) {
            showImages(vpage, uploadedIds, imageTable, viewServletPath);
        }
        servletSupport.showPage(response);
    } catch (FileUploadException ex) {
        Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:ke.co.tawi.babblesms.server.servlet.upload.ContactUpload.java

/**
 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///from   w  w w .  j a  v a  2s.co  m
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    File uploadedFile = null;

    List<String> groupUuids = new LinkedList<>();
    Account account = new Account();

    HttpSession session = request.getSession(false);

    String username = (String) session.getAttribute(SessionConstants.ACCOUNT_SIGN_IN_KEY);

    Element element;
    if ((element = accountsCache.get(username)) != null) {
        account = (Account) element.getObjectValue();
    }

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Set up where the files will be stored on disk
    File repository = new File(System.getProperty("java.io.tmpdir") + File.separator + username);
    FileUtils.forceMkdir(repository);
    factory.setRepository(repository);

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Parse the request              
    try {
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iter = items.iterator();

        FileItem item;

        while (iter.hasNext()) {
            item = iter.next();

            if (item.isFormField()) {
                // Here we assume only a Group UUID has been submitted as a text field
                groupUuids.add(item.getString());

            } else {
                uploadedFile = processUploadedFile(item);
            }
        } // end 'while (iter.hasNext())'

    } catch (FileUploadException e) {
        logger.error("FileUploadException while getting File Items.");
        logger.error(e);
    }

    // Here we assume that only one file was uploaded
    // First we inspect if it is ok
    String feedback = uploadUtil.inspectContactFile(uploadedFile);
    session.setAttribute(UPLOAD_FEEDBACK, "<p class='error'>" + feedback + "<p>");

    response.sendRedirect("addcontact.jsp");

    // Process the file into the database if it is ok
    if (StringUtils.equals(feedback, UPLOAD_SUCCESS)) {
        uploadUtil.saveContacts(uploadedFile, account, contactDAO, phoneDAO, groupUuids, contactGroupDAO);
    }
}

From source file:com.gwtcx.server.servlet.FileUploadServlet.java

@SuppressWarnings("rawtypes")
private void processFiles(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // set the size threshold, above which content will be stored on disk
    factory.setSizeThreshold(1 * 1024 * 1024); // 1 MB

    // set the temporary directory (this is where files that exceed the threshold will be stored)
    factory.setRepository(tmpDir);// www .  j a  v  a 2 s.c o m

    // create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    try {
        String recordType = "Account";

        // parse the request
        List items = upload.parseRequest(request);

        // process the uploaded items
        Iterator itr = items.iterator();

        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();

            // process a regular form field
            if (item.isFormField()) {
                Log.debug("Field Name: " + item.getFieldName() + ", Value: " + item.getString());

                if (item.getFieldName().equals("recordType")) {
                    recordType = item.getString();
                }
            } else { // process a file upload

                Log.debug("Field Name: " + item.getFieldName() + ", Value: " + item.getName()
                        + ", Content Type: " + item.getContentType() + ", In Memory: " + item.isInMemory()
                        + ", File Size: " + item.getSize());

                // write the uploaded file to the application's file staging area
                File file = new File(destinationDir, item.getName());
                item.write(file);

                // import the CSV file
                importCsvFile(recordType, file.getPath());

                // file.delete();  // TO DO
            }
        }
    } catch (FileUploadException e) {
        Log.error("Error encountered while parsing the request", e);
    } catch (Exception e) {
        Log.error("Error encountered while uploading file", e);
    }
}

From source file:com.xclinical.mdr.server.DocumentServlet.java

@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    try {// w  w  w. ja v a  2 s. c o  m
        if (ServletFileUpload.isMultipartContent(req)) {
            log.debug("detected multipart content");

            final FileInfo info = new FileInfo();

            ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory());

            @SuppressWarnings("unchecked")
            List<FileItem> items = fileUpload.parseRequest(req);

            String session = null;

            for (Iterator<FileItem> i = items.iterator(); i.hasNext();) {
                log.debug("detected form field");

                FileItem item = (FileItem) i.next();

                if (item.isFormField()) {
                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString();

                    if (fieldName != null) {
                        log.debug("{0}={1}", fieldName, fieldValue);
                    } else {
                        log.severe("fieldName may not be null");
                    }

                    if ("session".equals(fieldName)) {
                        session = fieldValue;
                    }
                } else {
                    log.debug("detected content");

                    info.contentName = item.getName();
                    info.contentName = new File(info.contentName).getName();
                    info.contentType = item.getContentType();
                    info.content = item.get();

                    log.debug("{0} bytes", info.content.length);
                }
            }

            if (info.content == null)
                throw new IllegalArgumentException("there is no content");
            if (info.contentType == null)
                throw new IllegalArgumentException("There is no content type");
            if (info.contentName == null)
                throw new IllegalArgumentException("There is no content name");

            Session.runInSession(session, new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    Document document = Document.create(info.contentName, info.contentType, info.content);

                    log.info("Created document " + document.getId());

                    ReferenceDocument referenceDocument = saveFile(req, document);

                    JsonCommandServlet.writeResponse(resp, FlatJsonExporter.of(referenceDocument));
                    return null;
                }
            });
        } else {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }

    } catch (FileUploadException e) {
        log.severe(e);
        throw new ServletException(e);
    } catch (Exception e) {
        log.severe(e);
        throw new ServletException(e);
    }
}

From source file:com.liferay.faces.bridge.context.map.MultiPartFormDataProcessorImpl.java

@Override
public Map<String, Collection<UploadedFile>> process(ClientDataRequest clientDataRequest,
        PortletConfig portletConfig, FacesRequestParameterMap facesRequestParameterMap) {

    Map<String, Collection<UploadedFile>> uploadedFileMap = null;

    PortletSession portletSession = clientDataRequest.getPortletSession();

    String uploadedFilesDir = PortletConfigParam.UploadedFilesDir.getStringValue(portletConfig);

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

    // 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]", StringPool.BLANK);

    File uploadedFilesPath = new File(uploadedFilesDir, sessionId);

    if (!uploadedFilesPath.exists()) {
        uploadedFilesPath.mkdirs();/* w  ww .  jav a 2  s.  c  om*/
    }

    // 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 = PortletConfigParam.UploadedFileMaxSize.getIntegerValue(portletConfig);

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

    // FACES-271: Include name+value pairs found in the ActionRequest.
    Set<Map.Entry<String, String[]>> actionRequestParameterSet = clientDataRequest.getParameterMap().entrySet();

    for (Map.Entry<String, String[]> mapEntry : actionRequestParameterSet) {

        String parameterName = mapEntry.getKey();
        String[] parameterValues = mapEntry.getValue();

        if (parameterValues.length > 0) {

            for (String parameterValue : parameterValues) {
                facesRequestParameterMap.addValue(parameterName, parameterValue);
            }
        }
    }

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

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

        if (clientDataRequest instanceof ResourceRequest) {
            ResourceRequest resourceRequest = (ResourceRequest) clientDataRequest;
            fileItemIterator = portletFileUpload.getItemIterator(new ActionRequestAdapter(resourceRequest));
        } else {
            ActionRequest actionRequest = (ActionRequest) clientDataRequest;
            fileItemIterator = portletFileUpload.getItemIterator(actionRequest);
        }

        boolean optimizeNamespace = PortletConfigParam.OptimizePortletNamespace.getBooleanValue(portletConfig);

        if (fileItemIterator != null) {

            int totalFiles = 0;
            String namespace = facesRequestParameterMap.getNamespace();

            // 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();

                    // If namespace optimization is enabled and the namespace is present in the field name,
                    // then remove the portlet namespace from the field name.
                    if (optimizeNamespace) {
                        int pos = fieldName.indexOf(namespace);

                        if (pos >= 0) {
                            fieldName = fieldName.substring(pos + namespace.length());
                        }
                    }

                    // 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 simple form-field, then save the form field value in the map.
                    if (diskFileItem.isFormField()) {
                        String characterEncoding = clientDataRequest.getCharacterEncoding();
                        String requestParameterValue = null;

                        if (characterEncoding == null) {
                            requestParameterValue = diskFileItem.getString();
                        } else {
                            requestParameterValue = diskFileItem.getString(characterEncoding);
                        }

                        facesRequestParameterMap.addValue(fieldName, requestParameterValue);
                    } else {

                        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);

                            facesRequestParameterMap.addValue(fieldName, copiedFileAbsolutePath);
                            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.ikon.servlet.admin.CssServlet.java

@Override
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = WebUtils.getString(request, "action");
    String userId = request.getRemoteUser();
    updateSessionManager(request);//from   w  ww . j  ava 2 s.c o m

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            Css css = new Css();
            css.setActive(false);

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

                if (item.isFormField()) {
                    if (item.getFieldName().equals("action")) {
                        action = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("css_id")) {
                        if (!item.getString("UTF-8").isEmpty()) {
                            css.setId(new Long(item.getString("UTF-8")).longValue());
                        }
                    } else if (item.getFieldName().equals("css_name")) {
                        css.setName(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("css_context")) {
                        css.setContext(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("css_content")) {
                        css.setContent(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("css_active")) {
                        css.setActive(true);
                    }
                }
            }

            if (action.equals("edit")) {
                CssDAO.getInstance().update(css);

                // Activity log
                UserActivity.log(userId, "ADMIN_CSS_UPDATE", String.valueOf(css.getId()), null, css.getName());
            } else if (action.equals("delete")) {
                String name = WebUtils.getString(request, "css_name");
                CssDAO.getInstance().delete(css.getId());

                // Activity log
                UserActivity.log(userId, "ADMIN_CSS_DELETE", String.valueOf(css.getId()), null, name);
            } else if (action.equals("create")) {
                long id = CssDAO.getInstance().create(css);

                // Activity log
                UserActivity.log(userId, "ADMIN_CSS_CREATE", String.valueOf(id), null, css.getName());
            }
        }

        list(userId, request, response);
    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    }
}

From source file:it.vige.greenarea.sgrl.servlet.CommonsFileUploadServlet.java

protected void workingdoPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("text/plain");
    out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>");
    out.println();//from   w  ww .jav  a 2  s .c  o m

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    /*
     * 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.
     */
    fileItemFactory.setRepository(tmpDir);

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    try {
        /*
         * Parse the request
         */
        List<FileItem> items = uploadHandler.parseRequest(request);
        Iterator<FileItem> itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            /*
             * Handle Form Fields.
             */
            if (item.isFormField()) {
                out.println("File Name = " + item.getFieldName() + ", Value = " + item.getString());
            } else {
                // Handle Uploaded files.
                out.println("Field Name = " + item.getFieldName() + ", File Name = " + item.getName()
                        + ", Content type = " + item.getContentType() + ", File Size = " + item.getSize());
                /*
                 * Write file to the ultimate location.
                 */
                File file = new File(destinationDir, "LogisticNetwork.mxe");
                item.write(file);
            }
            out.close();
        }
    } catch (FileUploadException ex) {
        log("Error encountered while parsing the request", ex);
    } catch (Exception ex) {
        log("Error encountered while uploading file", ex);
    }

}

From source file:com.beetle.framework.web.controller.UploadController.java

/**
 * use the overdue upload package/*from   w w w. j  a  v  a  2 s  .c om*/
 * 
 * @param webInput
 * @param request
 * @return
 * @throws ControllerException
 */
private View doupload(WebInput webInput, HttpServletRequest request) throws ControllerException {
    UploadForm fp = null;
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload sfu = new ServletFileUpload(factory);
    List<?> fileItems = null;
    boolean openApiCase = false;
    try {
        IUpload upload = (IUpload) webInput.getRequest().getAttribute("UPLOAD_CTRL_IOBJ");
        if (upload == null) {
            logger.debug("get upload from :{}", webInput.getControllerName());
            String ctrlimpName = (String) webInput.getRequest().getAttribute(CommonUtil.controllerimpclassname);
            if (ctrlimpName != null)
                upload = UploadFactory.getUploadInstance(webInput.getControllerName(), ctrlimpName); // 2007-03-21
            serviceInject(upload);
        }
        if (upload == null) {
            String uploadclass = webInput.getParameter("$upload");
            if (uploadclass == null || uploadclass.trim().length() == 0) {
                throw new ControllerException("upload dealer can't not found!");
            }
            openApiCase = true;
            String uploadclass_ = ControllerFactory.composeClassImpName(webInput.getRequest(), uploadclass);
            logger.debug("uploadclass:{}", uploadclass);
            logger.debug("uploadclass_:{}", uploadclass_);
            upload = UploadFactory.getUploadInstance(uploadclass, uploadclass_);
            serviceInject(upload);
        }
        logger.debug("IUpload:{}", upload);
        long sizeMax = webInput.getParameterAsLong("sizeMax", 0);
        if (sizeMax == 0) {
            sfu.setSizeMax(IUpload.sizeMax);
        } else {
            sfu.setSizeMax(sizeMax);
        }
        int sizeThreshold = webInput.getParameterAsInteger("sizeThreshold", 0);
        if (sizeThreshold == 0) {
            factory.setSizeThreshold(IUpload.sizeThreshold);
        } else {
            factory.setSizeThreshold(sizeThreshold);
        }
        Map<String, String> fieldMap = new HashMap<String, String>();
        List<FileObj> fileList = new ArrayList<FileObj>();
        fileItems = sfu.parseRequest(request);
        Iterator<?> i = fileItems.iterator();
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (fi.isFormField()) {
                fieldMap.put(fi.getFieldName(), fi.getString());
            } else {
                fileList.add(new FileObj(fi));
            }
        }
        fp = new UploadForm(fileList, fieldMap, request, webInput.getResponse());
        View view = upload.processUpload(fp);
        if (view.getViewname() == null || view.getViewname().trim().equals("")) {
            // view.setViewName(AbnormalViewControlerImp.abnormalViewName);
            //
            if (openApiCase) {
                return view;
            }
            UpService us = new UpService(view);
            return us.perform(webInput);
        }
        return view;
    } catch (Exception ex) {
        logger.error("upload", ex);
        throw new ControllerException(WebConst.WEB_EXCEPTION_CODE_UPLOAD, ex);
    } finally {
        if (fileItems != null) {
            fileItems.clear();
        }
        if (fp != null) {
            fp.clear();
        }
        sfu = null;
    }
}