Example usage for org.apache.commons.fileupload.disk DiskFileItem write

List of usage examples for org.apache.commons.fileupload.disk DiskFileItem write

Introduction

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

Prototype

public void write(File file) throws Exception 

Source Link

Document

A convenience method to write an uploaded item to disk.

Usage

From source file:com.afspq.web.ProcessQuery.java

@SuppressWarnings({ "unused", "rawtypes" })
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {/*from  ww w  .jav a2s  .  co  m*/
            String root = getServletContext().getRealPath("/");
            File path = new File(root + "/uploads");
            List items = upload.parseRequest(request);

            if (!path.exists()) {
                boolean status = path.mkdirs();
            }

            if (items.size() > 0) {
                DiskFileItem file = (DiskFileItem) items.get(0);
                File uploadedFile = new File(path + "/" + file.getName());

                file.write(uploadedFile);
                request.setAttribute("results",
                        new ImageResults().getResults(uploadedFile, imageSearch, 0, true));
                request.getRequestDispatcher("imageResults.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.customer.FileSystemViewHandler.java

private Vector uploadTmpAttachmentFile(HttpServletRequest request, HttpSession session) {
    String tmpFoler = request.getParameter("folder");
    String uploadPath = AmbFileStoragePathUtils.getFileStorageDirPath() + File.separator + "GlobalSight"
            + File.separator + "CommentReference" + File.separator + "tmp" + File.separator + tmpFoler;
    try {/*ww w .  j  a  va2 s.co m*/
        boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
        if (isMultiPart) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1024000);
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);

            for (int i = 0; i < items.size(); i++) {
                DiskFileItem item = (DiskFileItem) items.get(i);
                if (!item.isFormField()) {
                    String fileName = item.getFieldName();
                    String filePath = uploadPath + File.separator + fileName;
                    File f = new File(filePath);
                    f.getParentFile().mkdirs();
                    item.write(f);
                }
            }
        }
    } catch (Exception e) {
        throw new EnvoyServletException(e);
    }
    return new Vector();
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.customer.FileSystemViewHandler.java

/**
 * Save the files to the docs directory.
 */// w  w w.  j  a  va 2 s .  c  o m
private Vector saveData(HttpServletRequest p_request, HttpSession p_session)
        throws EnvoyServletException, IOException {
    Vector outData = null;
    SessionManager sessionMgr = (SessionManager) p_session.getAttribute(SESSION_MANAGER);
    String jobName = (String) sessionMgr.getAttribute("jobName");
    String srcLocale = (String) sessionMgr.getAttribute("srcLocale");

    TimeZone tz = (TimeZone) p_session.getAttribute(WebAppConstants.USER_TIME_ZONE);
    long uploadDateInLong = System.currentTimeMillis();
    Date uploadDate = new Date(uploadDateInLong);
    String uploadPath = getUploadPath(jobName, srcLocale, uploadDate);
    try {
        boolean isMultiPart = ServletFileUpload.isMultipartContent(p_request);
        if (isMultiPart) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1024000);
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(p_request);

            List<String> files = null;
            for (int i = 0; i < items.size(); i++) {
                DiskFileItem item = (DiskFileItem) items.get(i);
                if (!item.isFormField()) {
                    StringBuffer sb = new StringBuffer();
                    sb.append(uploadPath);
                    sb.append(File.separator);
                    sb.append("GS_");
                    sb.append(System.currentTimeMillis());
                    sb.append(".zip");
                    String fileName = sb.toString();
                    File f = new File(fileName);
                    f.getParentFile().mkdirs();
                    item.write(f);
                    files = ZipIt.unpackZipPackage(fileName);

                    f.delete();
                    sessionMgr.setAttribute("numOfFiles", String.valueOf(files.size()));
                }
            }
            // now update the job name to include the timestamp
            String newJobName = uploadPath.substring(uploadPath.lastIndexOf(File.separator) + 1,
                    uploadPath.length());
            sessionMgr.setAttribute("jobName", newJobName);

            saveJobNote(sessionMgr, newJobName, uploadDateInLong);

            sendUploadCompletedEmail(files, sessionMgr, uploadDate, tz,
                    (Locale) p_session.getAttribute(WebAppConstants.UILOCALE));
        }

        return outData;
    } catch (Exception ex) {
        throw new EnvoyServletException(ex);
    }
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.customer.FileSystemViewHandler.java

private Vector uploadTmpFiles(HttpServletRequest request, HttpSession session) {
    String tmpFoler = request.getParameter("folder");
    String uploadPath = AmbFileStoragePathUtils.getCxeDocDir() + File.separator
            + CreateJobsMainHandler.TMP_FOLDER_NAME + File.separator + tmpFoler;
    try {//from   w  w w .  j a va 2s  . c  o m
        boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
        if (isMultiPart) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1024000);
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);

            for (int i = 0; i < items.size(); i++) {
                DiskFileItem item = (DiskFileItem) items.get(i);
                if (!item.isFormField()) {
                    String filePath = item.getFieldName();
                    if (filePath.contains(":")) {
                        filePath = filePath.substring(filePath.indexOf(":") + 1);
                    }
                    String originalFilePath = filePath.replace("\\", File.separator).replace("/",
                            File.separator);
                    String fileName = uploadPath + File.separator + originalFilePath;
                    File f = new File(fileName);
                    f.getParentFile().mkdirs();
                    item.write(f);

                    String extension = FileUtils.getFileExtension(f);
                    if (extension != null && extension.equalsIgnoreCase("zip")) {
                        unzipFile(f);
                        f.delete();
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new EnvoyServletException(e);
    }
    return new Vector();
}

From source file:org.forumj.web.servlet.post.SetAvatar.java

private String moveUploadedImage(Image image, Long photoId, String fileExtention, ImageSize imageSize,
        FileItem file) throws Exception {
    String imagePath = makeAvatarPath(photoId);
    checkAndCreateImagePath(imagePath);//from  www  . j a v  a 2  s .c  o m
    String fileName = makeImageName(photoId, imagePath, fileExtention);
    File destFile = new File(fileName);
    DiskFileItem item = (DiskFileItem) file;
    item.write(destFile);
    return makeImageName(photoId, makeAvatarUrl(photoId), fileExtention);
}

From source file:org.infoglue.calendar.actions.CalendarUploadAbstractAction.java

public File getFile() {
    try {//from w ww . j  a v  a 2s .  co m
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Configure the factory here, if desired.
        PortletFileUpload upload = new PortletFileUpload(factory);
        // Configure the uploader here, if desired.
        List fileItems = upload.parseRequest(ServletActionContext.getRequest());
        log.debug("fileItems:" + fileItems.size());
        Iterator i = fileItems.iterator();
        while (i.hasNext()) {
            Object o = i.next();
            DiskFileItem dfi = (DiskFileItem) o;
            log.debug("dfi:" + dfi.getFieldName());
            log.debug("dfi:" + dfi);

            if (!dfi.isFormField()) {
                String fieldName = dfi.getFieldName();
                String fileName = dfi.getName();
                String contentType = dfi.getContentType();
                boolean isInMemory = dfi.isInMemory();
                long sizeInBytes = dfi.getSize();

                log.debug("fieldName:" + fieldName);
                log.debug("fileName:" + fileName);
                log.debug("contentType:" + contentType);
                log.debug("isInMemory:" + isInMemory);
                log.debug("sizeInBytes:" + sizeInBytes);
                File uploadedFile = new File(getTempFilePath() + File.separator + fileName);
                dfi.write(uploadedFile);
                return uploadedFile;
            }

        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return file;
}

From source file:org.infoglue.calendar.actions.CreateResourceAction.java

/**
 * This is the entry point for the main listing.
 *///from w w  w  .ja v a 2s  . c  o  m

public String execute() throws Exception {
    log.debug("-------------Uploading file.....");

    File uploadedFile = null;
    String maxUploadSize = "";
    String uploadSize = "";

    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(2000000);
        //factory.setRepository(yourTempDirectory);

        PortletFileUpload upload = new PortletFileUpload(factory);

        String maxSize = getSetting("AssetUploadMaxFileSize");
        log.debug("maxSize:" + maxSize);
        if (maxSize != null && !maxSize.equals("") && !maxSize.equals("@AssetUploadMaxFileSize@")) {
            try {
                maxUploadSize = maxSize;
                upload.setSizeMax((new Long(maxSize) * 1000));
            } catch (Exception e) {
                log.warn("Faulty max size parameter sent from portlet component:" + maxSize);
            }
        } else {
            maxSize = "" + (10 * 1024);
            maxUploadSize = maxSize;
            upload.setSizeMax((new Long(maxSize) * 1000));
        }

        List fileItems = upload.parseRequest(ServletActionContext.getRequest());
        log.debug("fileItems:" + fileItems.size());
        Iterator i = fileItems.iterator();
        while (i.hasNext()) {
            Object o = i.next();
            DiskFileItem dfi = (DiskFileItem) o;
            log.debug("dfi:" + dfi.getFieldName());
            log.debug("dfi:" + dfi);

            if (dfi.isFormField()) {
                String name = dfi.getFieldName();
                String value = dfi.getString();
                uploadSize = "" + (dfi.getSize() / 1000);

                log.debug("name:" + name);
                log.debug("value:" + value);
                if (name.equals("assetKey")) {
                    this.assetKey = value;
                } else if (name.equals("eventId")) {
                    this.eventId = new Long(value);
                    ServletActionContext.getRequest().setAttribute("eventId", this.eventId);
                } else if (name.equals("calendarId")) {
                    this.calendarId = new Long(value);
                    ServletActionContext.getRequest().setAttribute("calendarId", this.calendarId);
                } else if (name.equals("mode"))
                    this.mode = value;
            } else {
                String fieldName = dfi.getFieldName();
                String fileName = dfi.getName();
                uploadSize = "" + (dfi.getSize() / 1000);

                this.fileName = fileName;
                log.debug("FileName:" + this.fileName);
                uploadedFile = new File(getTempFilePath() + File.separator + fileName);
                dfi.write(uploadedFile);
            }

        }
    } catch (Exception e) {
        ServletActionContext.getRequest().getSession().setAttribute("errorMessage",
                "Exception uploading resource. " + e.getMessage() + ".<br/>Max upload size: " + maxUploadSize
                        + " KB"); // + "<br/>Attempted upload size (in KB):" + uploadSize);
        ActionContext.getContext().getValueStack().getContext().put("errorMessage",
                "Exception uploading resource. " + e.getMessage() + ".<br/>Max upload size: " + maxUploadSize
                        + " KB"); // + "<br/>Attempted upload size (in KB):" + uploadSize);
        log.error("Exception uploading resource. " + e.getMessage());
        return Action.ERROR;
    }

    try {
        log.debug("Creating resources.....:" + this.eventId + ":"
                + ServletActionContext.getRequest().getParameter("eventId") + ":"
                + ServletActionContext.getRequest().getParameter("calendarId"));
        ResourceController.getController().createResource(this.eventId, this.getAssetKey(),
                this.getFileContentType(), this.getFileName(), uploadedFile, getSession());
    } catch (Exception e) {
        ServletActionContext.getRequest().getSession().setAttribute("errorMessage",
                "Exception saving resource to database: " + e.getMessage());
        ActionContext.getContext().getValueStack().getContext().put("errorMessage",
                "Exception saving resource to database: " + e.getMessage());
        log.error("Exception saving resource to database. " + e.getMessage());
        return Action.ERROR;
    }

    return Action.SUCCESS;
}

From source file:org.infoglue.calendar.actions.UpdateEventAction.java

/**
 * This is the entry point for the main listing.
 *///from  w  ww .  j av a  2  s .c o m

public String upload() throws Exception {

    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Configure the factory here, if desired.
        PortletFileUpload upload = new PortletFileUpload(factory);
        // Configure the uploader here, if desired.
        List fileItems = upload.parseRequest(ServletActionContext.getRequest());
        log.debug("fileItems:" + fileItems.size());
        Iterator i = fileItems.iterator();
        while (i.hasNext()) {
            Object o = i.next();
            DiskFileItem dfi = (DiskFileItem) o;
            log.debug("dfi:" + dfi.getFieldName());
            log.debug("dfi:" + dfi);

            if (!dfi.isFormField()) {
                String fieldName = dfi.getFieldName();
                String fileName = dfi.getName();
                String contentType = dfi.getContentType();
                boolean isInMemory = dfi.isInMemory();
                long sizeInBytes = dfi.getSize();

                log.debug("fieldName:" + fieldName);
                log.debug("fileName:" + fileName);
                log.debug("contentType:" + contentType);
                log.debug("isInMemory:" + isInMemory);
                log.debug("sizeInBytes:" + sizeInBytes);
                File uploadedFile = new File(getTempFilePath() + File.separator + fileName);
                dfi.write(uploadedFile);
            }

        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    log.debug("");
    ResourceController.getController().createResource(this.eventId, this.getAssetKey(),
            this.getFileContentType(), this.getFileFileName(), this.getFile(), getSession());

    return "successUpload";
}

From source file:org.infoglue.cms.util.FileUploadHelper.java

/**
 * Lists the files//from   w ww  .  ja  v  a2  s.c  o m
 */

public static void listMultiPartFiles(HttpServletRequest req) {
    try {
        File tempDir = new File("c:/temp/uploads");
        logger.info("tempDir:" + tempDir.exists());

        DiskFileItemFactory factory = new DiskFileItemFactory(1000, tempDir);
        ServletFileUpload upload = new ServletFileUpload(factory);
        if (ServletFileUpload.isMultipartContent((HttpServletRequest) req)) {
            List fileItems = upload.parseRequest((HttpServletRequest) req);
            logger.info("******************************");
            logger.info("fileItems:" + fileItems.size());
            logger.info("******************************");
            req.setAttribute("Test", "Mattias Testar");

            Iterator i = fileItems.iterator();
            while (i.hasNext()) {
                Object o = i.next();
                DiskFileItem dfi = (DiskFileItem) o;
                logger.info("dfi:" + dfi.getFieldName());
                logger.info("dfi:" + dfi);

                if (!dfi.isFormField()) {
                    String fieldName = dfi.getFieldName();
                    String fileName = dfi.getName();
                    String contentType = dfi.getContentType();
                    boolean isInMemory = dfi.isInMemory();
                    long sizeInBytes = dfi.getSize();

                    logger.info("fieldName:" + fieldName);
                    logger.info("fileName:" + fileName);
                    logger.info("contentType:" + contentType);
                    logger.info("isInMemory:" + isInMemory);
                    logger.info("sizeInBytes:" + sizeInBytes);
                    File uploadedFile = new File("c:/temp/uploads/" + fileName);
                    dfi.write(uploadedFile);

                    req.setAttribute(dfi.getFieldName(), uploadedFile.getAbsolutePath());
                }

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.mortbay.servlet.LLabsMultiPartFilter.java

/**
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 *///from w ww. ja v a2s  . c o m
@SuppressWarnings("unchecked")
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    logger.info("Received uploadRequest:" + request);
    if (Log.isDebugEnabled())
        Log.debug(getClass().getName() + ">>> Received Request");

    HttpServletRequest srequest = (HttpServletRequest) request;
    if (srequest.getContentType() == null || !srequest.getContentType().startsWith("multipart/form-data")) {
        chain.doFilter(request, response);
        return;
    }
    if (ServletFileUpload.isMultipartContent(srequest)) {
        // Parse the request

        List<File> tempFiles = new ArrayList<File>();
        try {

            MultiMap params = new MultiMap();

            logger.info("Parsing Request");

            List<DiskFileItem> fileItems = uploadHandler.parseRequest(srequest);

            logger.info("Done Parsing Request, got FileItems:" + fileItems);

            StringBuilder filenames = new StringBuilder();

            for (final DiskFileItem diskFileItem : fileItems) {
                if (diskFileItem.getName() == null && diskFileItem.getFieldName() != null
                        && diskFileItem.getFieldName().length() > 0) {
                    params.put(diskFileItem.getFieldName(), diskFileItem.getString());
                    continue;
                }
                if (diskFileItem.getName() == null)
                    continue;
                final File tempFile = File.createTempFile("upload" + diskFileItem.getName(), ".tmp");
                tempFiles.add(tempFile);

                diskFileItem.write(tempFile);
                request.setAttribute(diskFileItem.getName(), tempFile);
                filenames.append(diskFileItem.getName()).append(",");
            }
            params.put("Filenames", filenames.toString());
            logger.info("passing on filter");
            chain.doFilter(new Wrapper(srequest, params), response);

            for (final DiskFileItem diskFileItem : fileItems) {
                diskFileItem.delete();
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
            Log.warn(getClass().getName() + "MPartRequest, ERROR:" + e.getMessage());
            logger.error("FileUpload Failed", e);
            writeResponse((HttpServletResponse) response, HttpServletResponse.SC_EXPECTATION_FAILED);
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
            Log.warn(getClass().getName() + "MPartRequest, ERROR:" + e.getMessage());
            e.printStackTrace();
            writeResponse((HttpServletResponse) response, HttpServletResponse.SC_EXPECTATION_FAILED);
        } finally {
            for (File tempFile : tempFiles) {
                try {
                    tempFile.delete();
                } catch (Throwable t) {
                }
            }
        }
    }

}