Example usage for org.apache.commons.fileupload DiskFileUpload DiskFileUpload

List of usage examples for org.apache.commons.fileupload DiskFileUpload DiskFileUpload

Introduction

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

Prototype

public DiskFileUpload() 

Source Link

Document

Constructs an instance of this class which uses the default factory to create FileItem instances.

Usage

From source file:com.pureinfo.srm.RequestUtils.java

public static PureProperties parse(HttpServletRequest _request) throws PureException {
    logger.debug("enti");
    PureProperties props = new PureProperties();

    Enumeration names = _request.getParameterNames();
    logger.debug("enti11111111111#" + names.hasMoreElements());
    while (names.hasMoreElements()) {
        String sName = (String) names.nextElement();
        String[] values = _request.getParameterValues(sName);
        if (values.length == 1) {
            props.setProperty(sName, values[0]);
        } else {/*from  w  w  w . ja  v a  2 s  . co  m*/
            props.setProperty(sName, values);
        }

    }

    String sContentType = _request.getContentType();
    if (sContentType != null && sContentType.startsWith("multipart/form-data")) {
        logger.debug("enti111");
        DiskFileUpload upload = new DiskFileUpload();
        List items;
        try {
            items = upload.parseRequest(_request);
        } catch (FileUploadException ex) {
            throw new PureException(PureException.UNKNOWN, "upload error", ex);
        }
        logger.debug("enti111111111111" + items.size());
        for (Iterator iter = items.iterator(); iter.hasNext();) {
            FileItem item = (FileItem) iter.next();
            if (item.getName() == null) {
                props.setProperty(item.getFieldName(), item.getString());
            } else {
                props.setProperty(item.getFieldName(), item);
            }
            logger.debug("name:" + item.getFieldName() + "-value:" + props.getProperty(item.getFieldName()));
        }
    }

    return props;
}

From source file:com.krawler.esp.handlers.fileUploader.java

public static void parseRequest(HttpServletRequest request, HashMap<String, String> arrParam,
        ArrayList<FileItem> fi, boolean fileUpload) throws ServiceException {
    DiskFileUpload fu = new DiskFileUpload();
    FileItem fi1 = null;/*from   w  w w. ja  v  a2s.c  o  m*/
    List fileItems = null;
    try {
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        throw ServiceException.FAILURE("Admin.createUser", e);
    }
    for (Iterator k = fileItems.iterator(); k.hasNext();) {
        fi1 = (FileItem) k.next();
        if (fi1.isFormField()) {
            arrParam.put(fi1.getFieldName(), fi1.getString());
        } else {
            try {
                String fileName = new String(fi1.getName().getBytes(), "UTF8");
                if (fi1.getSize() != 0) {
                    fi.add(fi1);
                    fileUpload = true;
                }
            } catch (UnsupportedEncodingException ex) {
            }
        }
    }
}

From source file:productupdate.java

void getformdata() {
    try {/*from   w w w .jav  a  2 s .c o  m*/
        ServletContext x = this.getServletContext();
        String path = x.getRealPath("/images");

        System.out.println(path + " path");
        DiskFileUpload p = new DiskFileUpload();
        List q = p.parseRequest(request);
        Iterator z = q.iterator();
        while (z.hasNext()) {
            FileItem f = (FileItem) z.next();
            if (f.isFormField() == true) {
                //non-file data

                String h = f.getFieldName();
                String data = f.getString();
                if (h.equalsIgnoreCase("productid")) {
                    productid = data;
                } else if (h.equalsIgnoreCase("productname")) {
                    productname = data;

                } else if (h.equalsIgnoreCase("category")) {
                    categoryid = data;
                } else if (h.equalsIgnoreCase("price")) {
                    price = data;
                } else if (h.equalsIgnoreCase("description")) {
                    description = data;
                } else if (h.equalsIgnoreCase("status")) {
                    System.out.println("status " + status);
                    status = data;
                }
            } else {
                //file data
                String filename = f.getName();
                if (filename != null && filename.length() > 0) {
                    File g = new File(filename);

                    filename = g.getName();

                    //creating unique file name
                    long w = System.currentTimeMillis();
                    filename = w + filename;
                    System.out.println("path " + path + " file " + filename);
                    //upload file
                    File t = new File(path, filename);
                    f.write(t);
                    if (f.getFieldName().equals("image")) {
                        System.out.println("images " + image);
                        image = filename;
                    }
                }

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

}

From source file:productsave.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    try {/*from w w w  .j  a v  a 2s.  c  o m*/
        ServletContext x = this.getServletContext();
        String path = x.getRealPath("/images");

        System.out.println(path + " path");
        DiskFileUpload p = new DiskFileUpload();
        List q = p.parseRequest(request);
        Iterator z = q.iterator();
        while (z.hasNext()) {
            FileItem f = (FileItem) z.next();
            if (f.isFormField() == true) {
                //non-file data
                System.out.println("executed");
                String h = f.getFieldName();
                String data = f.getString();
                if (h.equalsIgnoreCase("productname")) {
                    productname = data;
                } else if (h.equalsIgnoreCase("category")) {
                    categoryid = data;
                    System.out.println(categoryid + " cccc");
                } else if (h.equalsIgnoreCase("price")) {
                    price = data;
                } else if (h.equalsIgnoreCase("description")) {
                    description = data;
                }

            } else {
                //file data
                String filename = f.getName();
                if (filename != null && filename.length() > 0) {
                    File g = new File(filename);

                    filename = g.getName();

                    //creating unique file name
                    long w = System.currentTimeMillis();
                    filename = w + filename;
                    System.out.println("path " + path + " file " + filename);
                    //upload file
                    File t = new File(path, filename);
                    f.write(t);
                    if (f.getFieldName().equals("image")) {
                        image = filename;
                    }
                }

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

    productbean product = new productbean();
    product.setProductname(productname);
    product.setCategoryid(categoryid);
    product.setDescription(description);
    product.setImage(image);
    product.setPrice(price);
    int count = product.save();
    if (count != 0) {
        out.println("1");
    } else {
        out.println("0");
    }
}

From source file:ca.myewb.frame.PostParamWrapper.java

public PostParamWrapper(HttpServletRequest request) throws Exception {
    if (!FileUpload.isMultipartContent(request)) {
        return;//from   w  ww. j  av  a2s  .  c om
    }

    DiskFileUpload upload = new DiskFileUpload();
    upload.setRepositoryPath(Helpers.getUserFilesDir() + "/temp");

    try {
        List items = upload.parseRequest(request);

        Iterator iter = items.iterator();

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

            if (item.isFormField()) {
                stringParams.put(item.getFieldName(), item.getString());
                allParams.put(item.getFieldName(), item);
            } else if (item.getSize() > 0) {
                fileParams.put(item.getFieldName(), item);
                allParams.put(item.getFieldName(), item);
            }
        }
    } catch (FileUploadException ex) {
        log.debug("The file upload exception returned the message: " + ex.getMessage());
        // Usually means user cancelled upload and connection timed out.
        // Do nothing.
    }
}

From source file:forseti.JUploadFichero.java

@SuppressWarnings("rawtypes")
public boolean procesaFicheros(HttpServletRequest req, PrintWriter out) {
    try {/*from   www.  jav a 2s .  co  m*/
        // construimos el objeto que es capaz de parsear la pericin
        DiskFileUpload fu = new DiskFileUpload();

        // maximo numero de bytes
        fu.setSizeMax(1024 * 512); // 512 K

        depura("Ponemos el tamao mximo");
        // tamao por encima del cual los ficheros son escritos directamente en disco
        fu.setSizeThreshold(4096);

        // directorio en el que se escribirn los ficheros con tamao superior al soportado en memoria
        fu.setRepositoryPath("/tmp");

        // ordenamos procesar los ficheros
        List fileItems = fu.parseRequest(req);

        if (fileItems == null) {
            depura("La lista es nula");
            return false;
        }

        // Iteramos por cada fichero

        Iterator i = fileItems.iterator();
        FileItem actual = null;
        depura("estamos en la iteracin");

        while ((actual = (FileItem) i.next()) != null) {
            String fileName = actual.getName();
            out.println("<br>Nos han subido el archivo: " + fileName);

            // construimos un objeto file para recuperar el trayecto completo
            File fichero = new File(fileName);
            depura("El nombre del fichero es " + fichero.getName());

            // nos quedamos solo con el nombre y descartamos el path
            fichero = new File("../tomcat/webapps/ROOT/forsetidoc/IMG/" + fichero.getName());

            // escribimos el fichero colgando del nuevo path
            actual.write(fichero);
        }

    } catch (Exception e) {
        if (e != null)
            depura("Error de Aplicacin " + e.getMessage());

        return false;
    }

    return true;
}

From source file:com.sun.licenseserver.License.java

/**
 * Construct a license object using the input provided in the 
 * request object,//from  w w w  . j  a v a  2s  . co  m
 * 
 * @param req
 */
public License(HttpServletRequest req) {
    if (FileUpload.isMultipartContent(req)) {
        DiskFileUpload upload = new DiskFileUpload();
        upload.setSizeMax(2 * 1024 * 1024);
        List items;
        try {
            items = upload.parseRequest(req);
        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return;
        }
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (!item.isFormField()) {
                if (item.getSize() > 2 * 1024 * 1024) {
                    continue;
                }
                m_log.fine("Size of uploaded license is [" + item.getSize() + "]");
                try {
                    license = item.getInputStream();
                    licSize = item.getSize();
                    mime = item.getContentType();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                    return;
                }

            } else {
                String name = item.getFieldName();
                String value = item.getString();
                m_log.fine("MC ItemName [" + name + "] Value[" + value + "]");
                if (name != null) {
                    if (name.equals("id")) {
                        id = value;
                        continue;
                    }
                    if (name.equals("userId")) {
                        userId = value;
                        continue;
                    }
                    if (name.equals("contentId")) {
                        contentId = value;
                        continue;
                    }
                    if (name.equals("shopId")) {
                        shopId = value;
                        continue;
                    }

                }
            }

        }
    }
}

From source file:com.krawler.esp.handlers.fileUploader.java

public static void parseRequest(HttpServletRequest request, HashMap<String, String> arrParam,
        ArrayList<FileItem> fi, boolean fileUpload, HashMap<Integer, String> filemap) throws ServiceException {
    DiskFileUpload fu = new DiskFileUpload();
    FileItem fi1 = null;//from ww w.  ja  v  a2  s  . c  om
    List fileItems = null;
    int i = 0;
    try {
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        throw ServiceException.FAILURE("Admin.createUser", e);
    }
    for (Iterator k = fileItems.iterator(); k.hasNext();) {
        fi1 = (FileItem) k.next();
        try {
            if (fi1.isFormField()) {
                arrParam.put(fi1.getFieldName(), fi1.getString("UTF-8"));
            } else {

                String fileName = new String(fi1.getName().getBytes(), "UTF8");
                if (fi1.getSize() != 0) {
                    fi.add(fi1);
                    filemap.put(i, fi1.getFieldName());
                    i++;
                    fileUpload = true;
                }
            }
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.krawler.esp.handlers.genericFileUpload.java

public void doPost(List fileItems, String filename, String destinationDirectory) {
    File destDir = new File(destinationDirectory);
    Ext = "";//from   w w  w. ja va2s.co  m
    if (!destDir.exists()) {
        destDir.mkdirs();
    }
    DiskFileUpload fu = new DiskFileUpload();
    fu.setSizeMax(-1);
    fu.setSizeThreshold(4096);
    fu.setRepositoryPath(destinationDirectory);
    for (Iterator i = fileItems.iterator(); i.hasNext();) {
        FileItem fi = (FileItem) i.next();
        if (!fi.isFormField()) {
            String fileName = null;
            try {
                fileName = new String(fi.getName().getBytes(), "UTF8");
                if (fileName.contains("."))
                    Ext = fileName.substring(fileName.lastIndexOf("."));
                if (fi.getSize() != 0) {
                    this.isUploaded = true;
                    File uploadFile = new File(destinationDirectory + "/" + filename + Ext);
                    fi.write(uploadFile);
                    imgResize(destinationDirectory + "/" + filename + Ext, 100, 100,
                            destinationDirectory + "/" + filename + "_100");
                    imgResize(destinationDirectory + "/" + filename + Ext, 35, 35,
                            destinationDirectory + "/" + filename);

                } else {
                    this.isUploaded = false;
                }
            } catch (Exception e) {
                logger.warn(e.getMessage(), e);
            }
        }
    }

}

From source file:com.krawler.svnwebclient.util.Uploader.java

public void doPost(HttpServletRequest request, HttpServletResponse responce, String destinationDirectory,
        String tempDirectory) throws SessionExpiredException {
    File tempDir = new File(tempDirectory);
    String sep = StorageHandler.GetFileSeparator();
    if (!tempDir.exists()) {
        tempDir.mkdirs();/* ww  w. ja va  2s.  c o  m*/
    }
    DiskFileUpload fu = new DiskFileUpload();
    // maximum size before a FileUploadException will be thrown
    fu.setSizeMax(-1);
    // maximum size that will be stored in memory
    fu.setSizeThreshold(4096);
    // the location for saving data that is larger than getSizeThreshold()
    fu.setRepositoryPath(tempDirectory);
    List fileItems = null;
    try {
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        Logger.getInstance(Uploader.class).error(e, e);
    }
    String docid1 = null;
    String docownerid = null;
    for (Iterator k = fileItems.iterator(); k.hasNext();) {
        FileItem fi1 = (FileItem) k.next();
        try {
            if (fi1.getFieldName().toString().equals("docid")) {
                docid1 = new String(fi1.getString().getBytes(), "UTF8");
            }
            if (fi1.getFieldName().toString().equals("docownerid")) {
                docownerid = new String(fi1.getString().getBytes(), "UTF8");
            }
        } catch (UnsupportedEncodingException e) {
            // Logger.getInstance(Uploader.class).error(e, e);
        }
    }
    if (docid1.equals("")) {
        docid1 = UUID.randomUUID().toString();
        this.setFlagType(true);
        docownerid = AuthHandler.getUserid(request);
    } else {
        this.setFlagType(false);
    }
    try {
        if (docownerid.equalsIgnoreCase("my")) {
            docownerid = AuthHandler.getUserid(request);
        }
        destinationDirectory = com.krawler.esp.handlers.StorageHandler.GetDocStorePath() + sep + docownerid;
    } catch (ConfigurationException ex) {
        this.isUploaded = false;
        this.errorMessage = "Problem occurred while uploading file";
        return;
    }
    File destDir = new File(destinationDirectory);
    if (!destDir.exists()) {
        destDir.mkdirs();
    }
    this.parameters.put("destinationDirectory", destinationDirectory);
    for (Iterator i = fileItems.iterator(); i.hasNext();) {
        FileItem fi = (FileItem) i.next();

        /*
         * try{ String docid1 = fi.getString("docid"); }catch(Exception e){}
         */
        if (fi.isFormField()) {
            try {
                if (fi.getFieldName().toString().equals("docid")
                        && new String(fi.getString().getBytes(), "UTF8").equals("")) {
                    this.parameters.put(fi.getFieldName(), docid1);
                } else {
                    this.parameters.put(fi.getFieldName(), new String(fi.getString().getBytes(), "UTF8"));
                }
            } catch (UnsupportedEncodingException e) {
                Logger.getInstance(Uploader.class).error(e, e);
            }
        } else {
            // filename on the client
            String fileName = null;

            try {
                fileName = new String(fi.getName().getBytes(), "UTF8");
                // org.tmatesoft.svn.core.internal.wc.SVNFileUtil.isExecutable(fi);
                String filext = "";
                if (fileName.contains("."))
                    filext = fileName.substring(fileName.lastIndexOf("."));

                if (fi.getSize() != 0) {
                    this.isUploaded = true;

                    // write the file
                    File uploadFile = new File(
                            destinationDirectory + sep + FileUtil.getLastPathElement(docid1 + filext));
                    fi.write(uploadFile);
                    this.parameters.put("svnName", uploadFile.getName());
                    if (filext.equals("")) {
                        this.parameters.put("fileExt", filext);
                    } else {
                        this.parameters.put("fileExt", filext.substring(1));
                    }
                } else {
                    this.isUploaded = false;
                    this.errorMessage = "Cannot upload a 0 byte file";
                }
            } catch (Exception e) {
                this.isUploaded = false;
                this.errorMessage = "Problem occurred while uploading file";
                Logger.getInstance(Uploader.class).error(e, e);
            }
            this.parameters.put(FormParameters.FILE_NAME, FileUtil.getLastPathElement(fileName));
        }
    }
}