Example usage for org.apache.commons.fileupload FileItem getSize

List of usage examples for org.apache.commons.fileupload FileItem getSize

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem getSize.

Prototype

long getSize();

Source Link

Document

Returns the size of the file item.

Usage

From source file:it.eng.spagobi.engines.dossier.modules.DossierManagementModule.java

private void loadPresentationTemplateHandler(SourceBean request, SourceBean response)
        throws SourceBeanException, EMFUserError {
    logger.debug("IN");
    try {/*  w w w.java2 s. c om*/
        String tempFolder = (String) request.getAttribute(DossierConstants.DOSSIER_TEMP_FOLDER);
        IDossierDAO dossierDao = new DossierDAOHibImpl();
        FileItem upFile = (FileItem) request.getAttribute("UPLOADED_FILE");
        if (upFile != null) {
            String fileName = GeneralUtilities.getRelativeFileNames(upFile.getName());
            if (upFile.getSize() == 0) {
                EMFValidationError error = new EMFValidationError(EMFErrorSeverity.ERROR, "uploadFile", "201");
                getErrorHandler().addError(error);
                return;
            }
            int maxSize = GeneralUtilities.getTemplateMaxSize();
            if (upFile.getSize() > maxSize) {
                EMFValidationError error = new EMFValidationError(EMFErrorSeverity.ERROR, "uploadFile", "202");
                getErrorHandler().addError(error);
                return;
            }
            if (!fileName.toUpperCase().endsWith(".PPT")) {
                List params = new ArrayList();
                params.add("ppt");
                EMFUserError error = new EMFValidationError(EMFErrorSeverity.ERROR, "UPLOADED_FILE", "107",
                        params, null, "component_dossier_messages");
                getErrorHandler().addError(error);
            } else {
                byte[] fileContent = upFile.get();
                dossierDao.storePresentationTemplateFile(fileName, fileContent, tempFolder);
            }
        } else {
            logger.warn("Upload file was null!!!");
        }

        //         UploadedFile upFile = (UploadedFile) request.getAttribute("UPLOADED_FILE");
        //         if (upFile != null) {
        //            String fileName = upFile.getFileName();
        //            if (!fileName.toUpperCase().endsWith(".PPT")) {
        //               List params = new ArrayList();
        //               params.add("ppt");
        //               EMFUserError error = new EMFValidationError(EMFErrorSeverity.ERROR, "UPLOADED_FILE", "107", params, null, "component_dossier_messages");
        //               getErrorHandler().addError(error);
        //            } else {
        //               byte[] fileContent = upFile.getFileContent();
        //               dossierDao.storePresentationTemplateFile(fileName, fileContent, tempFolder);
        //            }
        //         } else {
        //            logger.warn("Upload file was null!!!");
        //         }
        response.setAttribute(DossierConstants.PUBLISHER_NAME, "DossierLoopbackDossierDetail");
    } finally {
        logger.debug("OUT");
    }

}

From source file:adminShop.registraProducto.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from ww  w. ja  v  a2s  .c om*/
 *
 * @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 {
    String message = "Error";
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items;
        HashMap hm = new HashMap();
        ArrayList<Imagen> imgs = new ArrayList<>();
        Producto prod = new Producto();
        Imagen img = null;
        try {
            items = upload.parseRequest(request);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    String value = item.getString();
                    hm.put(name, value);
                } else {
                    img = new Imagen();
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    String contentType = item.getContentType();
                    boolean isInMemory = item.isInMemory();
                    long sizeBytes = item.getSize();
                    File file = new File("/home/gama/Escritorio/adoo/" + fileName + ".jpg");
                    item.write(file);
                    Path path = Paths.get("/home/gama/Escritorio/adoo/" + fileName + ".jpg");
                    byte[] data = Files.readAllBytes(path);
                    byte[] encode = org.apache.commons.codec.binary.Base64.encodeBase64(data);
                    img.setUrl(new javax.sql.rowset.serial.SerialBlob(encode));
                    imgs.add(img);
                    //file.delete();
                }
            }
            prod.setNombre((String) hm.get("nombre"));
            prod.setProdNum((String) hm.get("prodNum"));
            prod.setDesc((String) hm.get("desc"));
            prod.setIva(Double.parseDouble((String) hm.get("iva")));
            prod.setPrecio(Double.parseDouble((String) hm.get("precio")));
            prod.setPiezas(Integer.parseInt((String) hm.get("piezas")));
            prod.setEstatus("A");
            prod.setImagenes(imgs);
            ProductoDAO prodDAO = new ProductoDAO();
            if (prodDAO.registraProducto(prod)) {
                message = "Exito";
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    response.sendRedirect("index.jsp");
}

From source file:com.krawler.esp.portalmsg.Forum.java

public static String insertForumPost(Connection conn, HttpServletRequest request)
        throws ServiceException, ParseException, JSONException {
    org.apache.commons.fileupload.DiskFileUpload fu = new org.apache.commons.fileupload.DiskFileUpload();
    java.util.List fileItems = null;
    org.apache.commons.fileupload.FileItem fi = null;
    int sizeinmb = forummsgcomm.getmaxfilesize(conn, AuthHandler.getCompanyid(request, false));
    long maxsize = sizeinmb * 1024 * 1024;
    boolean fileupload = false;
    fu.setSizeMax(maxsize);//from   www  .  java 2s .c o m
    java.util.HashMap arrParam = new java.util.HashMap();
    JSONObject jobj = new JSONObject();
    try {
        fileItems = fu.parseRequest(request);
    } catch (org.apache.commons.fileupload.FileUploadException e) {
        com.krawler.utils.json.base.JSONObject jerrtemp = new com.krawler.utils.json.base.JSONObject();
        jerrtemp.put("Success", "Fail");
        jerrtemp.put("msg", "Problem while uploading file.");
        jobj.append("data", jerrtemp);
        return jobj.toString();
    }
    for (java.util.Iterator k = fileItems.iterator(); k.hasNext();) {
        fi = (org.apache.commons.fileupload.FileItem) k.next();
        arrParam.put(fi.getFieldName(), fi.getString());
        if (!fi.isFormField()) {
            if (fi.getSize() > maxsize) {
                com.krawler.utils.json.base.JSONObject jerrtemp = new com.krawler.utils.json.base.JSONObject();
                jerrtemp.put("Success", "Fail");
                jerrtemp.put("msg", "For attachments, maximum file size allowed is " + sizeinmb + " MB");
                jobj.append("data", jerrtemp);
                return jobj.toString();
            }
            fileupload = true;
        }
    }
    //                destinationDirectory = com.krawler.esp.handlers.StorageHandler
    //               .GetDocStorePath()
    int firstReply = Integer.parseInt(request.getParameter("firstReply"));
    String ptext = java.net.URLDecoder.decode(arrParam.get("ptxt").toString());
    String repto = request.getParameter("repto");
    String title = java.net.URLDecoder.decode(arrParam.get("title").toString());
    String u_id = request.getParameter("userId");
    String group_id = request.getParameter("groupId");
    DbResults rs = null;
    DbResults rs1 = null;
    DbResults rs2 = null;
    String post_id = UUID.randomUUID().toString();
    String topic_id = "1";
    String topic_title = null;
    String dateTime = null;
    String UserName = null;
    String Image = null;
    String query = null;
    JSONStringer j = new JSONStringer();

    String temp = null;
    title = StringUtil.serverHTMLStripper(title);

    group_id = StringUtil.serverHTMLStripper(group_id);
    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    java.util.Date d = new java.util.Date();
    java.sql.Timestamp sqlPostDate = new Timestamp(d.getTime());
    if (StringUtil.isNullOrEmpty(repto) /*|| StringUtil.isNullOrEmpty(title)*/ || StringUtil.isNullOrEmpty(u_id)
            || StringUtil.isNullOrEmpty(group_id)) {
        com.krawler.utils.json.base.JSONObject jerrtemp = new com.krawler.utils.json.base.JSONObject();
        jerrtemp.put("Success", "Fail");
        jobj.append("data", jerrtemp);
        return jobj.toString();
    }
    if (fileupload) {
        forummsgcomm.doPost(conn, fileItems, post_id, sqlPostDate, u_id, "");
    }
    if (firstReply == 0) {

        query = "INSERT INTO krawlerforum_topics(topic_id, group_id, topic_title, topic_poster, post_time, post_subject,post_text, ifread,flag) VALUES (?, ?, ?, ?, ?, ?,?, ?, ?)";
        DbUtil.executeUpdate(conn, query,
                new Object[] { post_id, group_id, title, u_id, sqlPostDate, ptext, ptext, false, false });

        post_id = "topic" + post_id;
    } else if (firstReply == 1) {
        repto = repto.substring(5);

        query = "INSERT INTO krawlerforum_posts(post_id, post_poster, topic_id, group_id, topic_title,post_time, post_subject, post_text, reply_to, flag, ifread,reply_to_post) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
        DbUtil.executeUpdate(conn, query, new Object[] { post_id, u_id, topic_id, group_id, topic_title,
                sqlPostDate, title, ptext, repto, false, false, "-999" });

        repto = "topic" + repto;
    } else if (firstReply == 2) {
        query = "INSERT INTO krawlerforum_posts(post_id, post_poster, topic_id, group_id, topic_title, post_time, post_subject, post_text, reply_to, flag, ifread,reply_to_post) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
        DbUtil.executeUpdate(conn, query, new Object[] { post_id, u_id, topic_id, group_id, topic_title,
                sqlPostDate, title, ptext, "1", false, false, repto });

    }

    query = "SELECT userlogin.username,image FROM users inner join userlogin on users.userid = userlogin.userid where users.userid=?;";
    rs2 = DbUtil.executeQuery(conn, query, u_id);

    if (rs2.next()) {
        UserName = (rs2.getString(1));
        Image = (rs2.getString(2));
    }
    String userTime = Timezone.toCompanyTimezone(conn, sqlPostDate.toString(),
            CompanyHandler.getCompanyByUser(conn, u_id));
    java.util.Date tempdate = sdf.parse(userTime);
    com.krawler.utils.json.base.JSONObject jtemp = new com.krawler.utils.json.base.JSONObject();
    jtemp.put("Success", "Success");
    jtemp.put("ID", post_id);
    jtemp.put("Subject", title);
    jtemp.put("Received", sdf.format(tempdate));
    jtemp.put("From", UserName);
    jtemp.put("Details", "");
    jtemp.put("Flag", "false");
    jtemp.put("Image", Image);
    jtemp.put("Parent", repto);
    jobj.append("data", jtemp);
    /*temp = j.object().key("Success").value("Success").key("ID").value(
    post_id).key("Subject").value(title).key("Received").value(
    sdf1.format(tempdate).toString()).key("From").value(UserName)
    .key("Details").value("").key("Flag").value("false").key(
    "Image").value(Image).key("Parent").value(repto)
    .endObject().toString();*/
    return jobj.toString();
}

From source file:com.cmart.PageControllers.SellItemImagesController.java

public void saveImages(String baseURL) {
    //System.out.println("sellitemimagecont: looking for image to upload!");
    //System.out.println("saving images :" + baseURL);
    baseURL = baseURL + "/" + GV.REMOTE_IMAGE_DIR + "/";

    // Special case for the thumbnail
    /*if(this.images.size()>1){
       FileItem image = this.images.get(0);
               //from   w  ww . j  a v  a  2s  . co  m
       //TODO: compress an image
       String[] ext = image.getName().split("\\.");
       int extIndex = ext.length>0 ? ext.length-1 : 0;
       String filename = this.itemID + "_" + 0 + "." + ext[extIndex];
       String URL = filename;
               
       // Setup the thumbnail file
       File file = new File(GlobalVars.localImageDir, filename);
       file.setReadable(true, false);
       file.setWritable(true, false);
               
       try {
    image.write(file);
            
    GlobalVars.db.insertThumbnail(this.itemID, URL);
       } catch (Exception e) {
    // TODO Auto-generated catch block
    this.errors.add(new Error("SellItemImagesController (saveImages): Could not save thumbnail", e));
    e.printStackTrace();
       }
    }*/
    boolean thumbnail = true;

    // Loop through all the images
    for (int i = 0; i < this.images.size(); i++) {
        FileItem image = this.images.get(i);

        //TODO: make number start from one and only count real images

        if (image.getSize() > 0) {
            // Make the file name and path
            String[] ext = image.getName().split("\\.");
            int extIndex = ext.length > 0 ? ext.length - 1 : 0;
            String filename = this.itemID + "_" + (i + 1) + "." + ext[extIndex];
            //String URL = filename;

            // Setup the image file
            //System.out.println("setting temp dir as the image");
            File file = new File(GV.LOCAL_TEMP_DIR, filename + "tmp");
            file.setReadable(true, false);
            file.setWritable(true, false);

            //System.out.println("URL :" + URL);
            //System.out.println("name :" + filename);
            //System.out.println("local :" + GV.LOCAL_IMAGE_DIR);
            //System.out.println("remote :" + GV.REMOTE_IMAGE_DIR);

            try {
                //System.out.println("doing db insert");
                GV.DB.insertImage(this.itemID, i + 1, filename, "");

                //System.out.println("saving image");
                image.write(file);

                //System.out.println("mkaing file in img dir");
                File file2 = new File(GV.LOCAL_IMAGE_DIR, filename);

                //System.out.println("doing the image resize");
                BufferedImage originalImage2 = ImageIO.read(file);
                int type2 = originalImage2.getType() == 0 ? BufferedImage.TYPE_INT_ARGB
                        : originalImage2.getType();

                //System.out.println("doing the image resize second step");
                BufferedImage resizeImageHintJpg2 = resizeImageWithHint(originalImage2, type2, 500, 450);
                ImageIO.write(resizeImageHintJpg2, "jpg", file2);

                try {
                    file.delete();
                } catch (Exception e) {

                }

                //System.out.println("sellitemimagecont: inserted an image!");

                if (thumbnail) {
                    //TODO: some image compression
                    String thumbName = this.itemID + "_" + 0 + "." + ext[extIndex];
                    GV.DB.insertThumbnail(this.itemID, thumbName);

                    //System.out.println("doing thumbnail");

                    File thumbFile = new File(GV.LOCAL_IMAGE_DIR, thumbName);

                    // Get a JPEG writer
                    // TODO: other formats??
                    /*ImageWriter writer = null;
                      Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
                      if (iter.hasNext()) {
                          writer = (ImageWriter)iter.next();
                      }
                            
                      // Set the output file
                      ImageOutputStream ios = ImageIO.createImageOutputStream(thumbFile);
                      writer.setOutput(ios);
                              
                      // Set the compression level
                      JPEGImageWriteParam imgparams = new JPEGImageWriteParam(Locale.getDefault());
                      imgparams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT) ;
                      imgparams.setCompressionQuality(128);
                              
                      // Write the compressed file
                      RenderedImage rendFile = ImageIO.read(file);
                      writer.write(null, new IIOImage(rendFile, null, null), imgparams);
                              
                              
                              
                            
                    // copy file
                    InputStream fin = new FileInputStream(file);
                    OutputStream fout = new FileOutputStream(thumbFile);
                    byte[] buff = new byte[1024];
                    int len;
                            
                    while((len = fin.read(buff)) > 0)
                         fout.write(buff, 0, len);
                            
                    fin.close();
                    fout.close();
                    */

                    BufferedImage originalImage = ImageIO.read(file2);
                    int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB
                            : originalImage.getType();

                    BufferedImage resizeImageHintJpg = resizeImageWithHint(originalImage, type, 100, 100);
                    ImageIO.write(resizeImageHintJpg, "jpg", thumbFile);

                    thumbnail = false;
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                this.errors.add(new Error("SellItemImagesController (saveImages): Could not save image", e));
                e.printStackTrace();
            }
        }
    }

    if (this.errors.size() == 0 && !this.useHTML5()) {
        createRedirectURL();
    }

    // Try to save the uploaded files
    /*try {
               
       while(images.hasNext()) {
    FileItem item = (FileItem) images.next();
    System.out.println("doing item 1");
    /*
     * Handle Form Fields.
     *
    if(item.isFormField()) {
       System.out.println("File Name = "+item.getFieldName()+", Value = "+item.getString());
    } else {
       //Handle Uploaded files.
       System.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(GlobalVars.imageDir,item.getName());
       item.write(file);
    }
    //System.out.close();
       }
    }catch(Exception ex) {
       System.out.println("Error encountered while uploading file");
    }*/
}

From source file:com.bluelotussoftware.apache.commons.fileupload.example.CommonsFileUploadServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("text/html");
    log("Content-Type: " + request.getContentType());

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    /*//  w  ww  .j a  v a  2  s. c om
     *Set the size threshold, above which content will be stored on disk.
     */
    fileItemFactory.setSizeThreshold(10 * 1024 * 1024); //10 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 items = uploadHandler.parseRequest(request);
        log("FileItems: " + items.toString());
        Iterator 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("<html><head><title>CommonsFileUploadServlet</title></head><body><p>");
                out.println("Field Name = " + item.getFieldName() + "\nFile Name = " + item.getName()
                        + "\nContent type = " + item.getContentType() + "\nFile Size = " + item.getSize());
                out.println("</p>");
                out.println("<img src=\"" + request.getContextPath() + "/files/" + item.getName() + "\"/>");
                out.println("</body></html>");
                /*
                 * Write file to the ultimate location.
                 */
                File file = new File(destinationDir, item.getName());
                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:fr.paris.lutece.plugins.directory.utils.DirectoryUtils.java

/**
 * Do download a file//w w  w .  jav a2s  . c o m
 *
 * @param strUrl
 *            the url of the file to download
 * @return a {@link FileItem}
 */
public static File doDownloadFile(String strUrl) {
    FileItem fileItem = null;
    File file = null;
    DirectoryAsynchronousUploadHandler handler = DirectoryAsynchronousUploadHandler.getHandler();

    try {
        fileItem = handler.doDownloadFile(strUrl);
    } catch (BlobStoreClientException e) {
        AppLogService.error(e);
    }

    if (fileItem != null) {
        if (fileItem.getSize() < Integer.MAX_VALUE) {
            PhysicalFile physicalFile = new PhysicalFile();
            physicalFile.setValue(fileItem.get());

            String strFileName = fileItem.getName();

            if (StringUtils.isNotBlank(strFileName)) {
                String strExtension = StringUtils.EMPTY;
                int nLastIndexOfDot = strFileName.lastIndexOf(CONSTANT_DOT);

                if (nLastIndexOfDot != DirectoryUtils.CONSTANT_ID_NULL) {
                    strExtension = strFileName.substring(nLastIndexOfDot + 1);
                }

                file = new File();
                file.setPhysicalFile(physicalFile);
                file.setSize((int) fileItem.getSize());
                file.setTitle(strFileName);

                if (StringUtils.isNotBlank(fileItem.getContentType())) {
                    file.setMimeType(fileItem.getContentType());
                } else {
                    file.setMimeType(FileSystemUtil.getMIMEType(strFileName));
                }

                file.setExtension(strExtension);
            }
        } else {
            AppLogService.error(
                    "DirectoryUtils : File too big ! fr.paris.lutece.plugins.directory.business.File.setSize "
                            + "must have Integer parameter, in other words a size lower than '"
                            + Integer.MAX_VALUE + "'");
        }
    }

    return file;
}

From source file:com.nemesis.admin.UploadServlet.java

/**
 * @param request// w  ww .  j av a  2 s  .co m
 * @param response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 * response)
 *
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new IllegalArgumentException(
                "Request is not multipart, please 'multipart/form-data' enctype for your form.");
    }

    ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
    PrintWriter writer = response.getWriter();
    response.setContentType("application/json");
    JsonArray json = new JsonArray();
    try {
        List<FileItem> items = uploadHandler.parseRequest(request);
        for (FileItem item : items) {
            if (!item.isFormField()) {
                final String savedFile = UUID.randomUUID().toString() + "." + getSuffix(item.getName());
                File file = new File(request.getServletContext().getRealPath("/") + "uploads/", savedFile);
                item.write(file);
                JsonObject jsono = new JsonObject();
                jsono.addProperty("name", savedFile);
                jsono.addProperty("path", file.getAbsolutePath());
                jsono.addProperty("size", item.getSize());
                json.add(jsono);
                System.out.println(json.toString());
            }
        }
    } catch (FileUploadException e) {
        throw new RuntimeException(e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        writer.write(json.toString());
        writer.close();
    }

}

From source file:com.silverpeas.form.displayers.ImageFieldDisplayer.java

private String processUploadedImage(List<FileItem> items, String parameterName, PagesContext pagesContext)
        throws IOException {
    String attachmentId = null;//  w w w . j a v a2s.  co  m
    FileItem item = FileUploadUtil.getFile(items, parameterName);
    if (item != null && !item.isFormField()) {
        String componentId = pagesContext.getComponentId();
        String userId = pagesContext.getUserId();
        String objectId = pagesContext.getObjectId();
        if (StringUtil.isDefined(item.getName())) {
            String fileName = FileUtil.getFilename(item.getName());
            long size = item.getSize();
            if (size > 0L) {
                SimpleDocument document = createSimpleDocument(objectId, componentId, item, fileName, userId);
                attachmentId = document.getId();
            }
        }
    }
    return attachmentId;
}

From source file:com.threecrickets.prudence.util.FormWithFiles.java

/**
 * Constructor.//from  ww w  .ja v  a 2s  . c  o m
 * 
 * @param webForm
 *        The URL encoded web form
 * @param fileItemFactory
 *        The file item factory
 * @throws ResourceException
 *         In case of an upload handling error
 */
public FormWithFiles(Representation webForm, FileItemFactory fileItemFactory) throws ResourceException {
    if (webForm.getMediaType().includes(MediaType.MULTIPART_FORM_DATA)) {
        RestletFileUpload fileUpload = new RestletFileUpload(fileItemFactory);

        try {
            for (FileItem fileItem : fileUpload.parseRepresentation(webForm)) {
                Parameter parameter;
                if (fileItem.isFormField())
                    parameter = new Parameter(fileItem.getFieldName(), fileItem.getString());
                else {
                    if (fileItem instanceof DiskFileItem) {
                        File file = ((DiskFileItem) fileItem).getStoreLocation();
                        if (file == null)
                            // In memory
                            parameter = new FileParameter(fileItem.getFieldName(), fileItem.get(),
                                    fileItem.getContentType(), fileItem.getSize());
                        else
                            // On disk
                            parameter = new FileParameter(fileItem.getFieldName(), file,
                                    fileItem.getContentType(), fileItem.getSize());
                    } else
                        // Non-file form item
                        parameter = new Parameter(fileItem.getFieldName(), fileItem.getString());
                }

                add(parameter);
            }
        } catch (FileUploadException x) {
            throw new ResourceException(x);
        }
    } else {
        // Default parsing
        addAll(new Form(webForm));
    }
}

From source file:de.betterform.agent.web.servlet.HttpRequestHandler.java

protected void processUploadParameters(Map uploads, HttpServletRequest request) throws XFormsException {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("updating " + uploads.keySet().size() + " uploads(s)");
    }/*w w  w .jav a 2 s  .  com*/

    try {
        // update repeat indices
        Iterator iterator = uploads.keySet().iterator();
        String id;
        FileItem item;
        byte[] data;

        while (iterator.hasNext()) {
            id = (String) iterator.next();
            item = (FileItem) uploads.get(id);

            if (item.getSize() > 0) {
                LOGGER.debug("i'm here");
                if (this.xformsProcessor.isFileUpload(id, "anyURI")) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("found upload type 'anyURI'");
                    }
                    String localPath = new StringBuffer().append(System.currentTimeMillis()).append('/')
                            .append(item.getName()).toString();

                    File localFile = new File(this.uploadRoot, localPath);
                    localFile.getParentFile().mkdirs();
                    item.write(localFile);

                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("saving data to path: " + localFile);
                    }

                    // todo: externalize file handling and uri generation

                    File uploadDir = new File(request.getContextPath(),
                            Config.getInstance().getProperty(WebFactory.UPLOADDIR_PROPERTY));
                    String urlEncodedPath = URLEncoder
                            .encode(new File(uploadDir.getPath(), localPath).getPath(), "UTF-8");
                    URI uploadTargetDir = new URI(urlEncodedPath);

                    data = uploadTargetDir.toString().getBytes();
                } else {
                    data = item.get();
                }

                this.xformsProcessor.setUploadValue(id, item.getContentType(), item.getName(), data);

                // After the value has been set and the RRR took place, create new UploadInfo with status set to 'done'
                request.getSession().setAttribute(WebProcessor.ADAPTER_PREFIX + sessionKey + "-uploadInfo",
                        new UploadInfo(1, 0, 0, 0, "done"));
            } else {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("ignoring empty upload " + id);
                }
                // todo: removal ?
            }

            item.delete();
        }
    } catch (Exception e) {
        throw new XFormsException(e);
    }
}