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:controladoresAdministrador.ControladorCargarInicial.java

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

    DiskFileItemFactory ff = new DiskFileItemFactory();

    ServletFileUpload sfu = new ServletFileUpload(ff);

    List items = null;
    File archivo = null;
    try {
        items = sfu.parseRequest(request);
    } catch (FileUploadException ex) {
        out.print(ex.getMessage());
    }
    String nombre = "";
    FileItem item = null;
    for (int i = 0; i < items.size(); i++) {

        item = (FileItem) items.get(i);

        if (!item.isFormField()) {
            nombre = item.getName();
            archivo = new File(this.getServletContext().getRealPath("/archivos/") + "/" + item.getName());
            try {
                item.write(archivo);
            } catch (Exception ex) {
                out.print(ex.getMessage());
            }
        }
    }
    CargaInicial carga = new CargaInicial();
    String ubicacion = archivo.toString();
    int cargado = carga.cargar(ubicacion);
    if (cargado == 1) {
        response.sendRedirect(
                "pages/indexadmin.jsp?msg=<strong><i class='glyphicon glyphicon-exclamation-sign'></i> No se encontro el archivo!</strong> Por favor intentelo de nuevo.&tipoAlert=warning");
    } else {
        response.sendRedirect(
                "pages/indexadmin.jsp?msg=<strong>Carga inicial exitosa! <i class='glyphicon glyphicon-ok'></i></strong>&tipoAlert=success");
    }
}

From source file:com.fatih.edu.tr.NewTaskServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (!isMultipart) {
        return;// w w w . j a  v a  2 s  .c  o  m
    }

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

    // Sets the size threshold beyond which files are written directly to
    // disk.
    factory.setSizeThreshold(MAX_MEMORY_SIZE);

    // Sets the directory used to temporarily store files that are larger
    // than the configured size threshold. We use temporary directory for
    // java
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    // constructs the folder where uploaded file will be stored
    String uploadFolder = getServletContext().getRealPath("") + File.separator + DATA_DIRECTORY;

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

    // Set overall request size constraint
    upload.setSizeMax(MAX_REQUEST_SIZE);

    TaskDao taskDao = new TaskDao();
    String title = "";
    String description = "";
    String due_date = "";
    String fileName = "";
    String filePath = "";
    //taskDao.addTask(title, description, due_date, "testfile","testdizi",1);

    try {
        // Parse the request
        List items = upload.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {

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

            if (!item.isFormField()) {
                fileName = new File(item.getName()).getName();
                filePath = uploadFolder + File.separator + fileName;
                File uploadedFile = new File(filePath);
                System.out.println(filePath);
                item.write(uploadedFile);
            } else {
                String fieldname = item.getFieldName();
                String fieldvalue = item.getString();
                if (fieldname.equals("title")) {
                    title = item.getString();
                } else if (fieldname.equals("description")) {
                    description = item.getString();

                } else if (fieldname.equals("due_date")) {
                    due_date = item.getString();
                } else {
                    System.out.println("Something goes wrong in form");
                }
            }

        }
        taskDao.addTask(title, description, due_date, fileName, filePath, 1);
        // displays done.jsp page after upload finished
        getServletContext().getRequestDispatcher("/done.jsp").forward(request, response);

    } catch (FileUploadException ex) {
        throw new ServletException(ex);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }

}

From source file:com.itpro.restws.helper.MultipartFromWrapper.java

/** Constructor. */
public MultipartFromWrapper(HttpServletRequest aRequest) throws IOException {
    super(aRequest);
    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    try {/* w  ww  .  java 2 s  .  c o  m*/
        List<FileItem> fileItems = upload.parseRequest(aRequest);
        convertToMaps(fileItems);
    } catch (FileUploadException ex) {
        throw new IOException("Cannot parse underlying request: " + ex.toString());
    }
}

From source file:edu.isi.webserver.FileUtil.java

static public File downloadFileFromHTTPRequest(HttpServletRequest request) {
    // Download the file to the upload file folder
    File destinationDir = new File(DESTINATION_DIR_PATH);
    logger.info("File upload destination directory: " + destinationDir.getAbsolutePath());
    if (!destinationDir.isDirectory()) {
        destinationDir.mkdir();//from  ww  w. j a  v  a  2s  .  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(destinationDir);

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);

    File uploadedFile = null;
    try {
        // Parse the request
        @SuppressWarnings("rawtypes")
        List items = uploadHandler.parseRequest(request);
        @SuppressWarnings("rawtypes")
        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();

            // Ignore Form Fields.
            if (item.isFormField()) {
                System.out.println(item.getFieldName());
                System.out.println(item.getString());
                // Do nothing
            } else {
                //Handle Uploaded files. Write file to the ultimate location.
                System.out.println("File field name: " + item.getFieldName());
                uploadedFile = new File(destinationDir, item.getName());
                item.write(uploadedFile);
                System.out.println("File written to: " + uploadedFile.getAbsolutePath());
            }
        }
    } catch (FileUploadException ex) {
        logger.error("Error encountered while parsing the request", ex);
    } catch (Exception ex) {
        logger.error("Error encountered while uploading file", ex);
    }
    return uploadedFile;
}

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

/**
 * Construction with default system repository directory.
 */
public PhpExecutionController() {
    this(new DiskFileItemFactory());
}

From source file:edu.caltech.ipac.firefly.server.servlets.FitsUpload.java

protected void processRequest(HttpServletRequest req, HttpServletResponse res) throws Exception {

    File dir = ServerContext.getVisUploadDir();
    File uploadedFile = getUniqueName(dir);

    String overrideKey = req.getParameter("cacheKey");

    DiskFileItemFactory factory = new DiskFileItemFactory();

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

    // Parse the request
    List /* FileItem */ items = upload.parseRequest(req);

    // Process the uploaded items
    Iterator iter = items.iterator();
    FileItem item = null;//from   w  w  w.j  a v a2s.  co  m
    if (iter.hasNext()) {
        item = (FileItem) iter.next();

        if (!item.isFormField()) {
            try {
                item.write(uploadedFile);
            } catch (Exception e) {
                sendReturnMsg(res, 500, e.getMessage(), null);
                return;
            }

        }
    }

    if (item == null) {
        sendReturnMsg(res, 500, "Could not find a upload file", null);
        return;
    }

    if (FileUtil.isGZipFile(uploadedFile)) {
        File uploadedFileZiped = new File(uploadedFile.getPath() + "." + FileUtil.GZ);
        uploadedFile.renameTo(uploadedFileZiped);
        FileUtil.gUnzipFile(uploadedFileZiped, uploadedFile, (int) FileUtil.MEG);
    }

    PrintWriter resultOut = res.getWriter();
    String retFile = ServerContext.replaceWithPrefix(uploadedFile);
    UploadFileInfo fi = new UploadFileInfo(retFile, uploadedFile, item.getName(), item.getContentType());
    String fileCacheKey = overrideKey != null ? overrideKey : retFile;
    UserCache.getInstance().put(new StringKey(fileCacheKey), fi);
    resultOut.println(fileCacheKey);
    String size = StringUtils.getSizeAsString(uploadedFile.length(), true);
    Logger.info("Successfully uploaded file: " + uploadedFile.getPath(), "Size: " + size);
    Logger.stats(Logger.VIS_LOGGER, "Fits Upload", "fsize", (double) uploadedFile.length() / StringUtils.MEG,
            "bytes", size);
}

From source file:com.ait.tooling.server.core.servlet.FileUploadServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.info("STARTING UPLOAD");

    try {/*from   ww w.  ja v  a  2s  .  c o  m*/
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

        ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory);

        fileUpload.setSizeMax(FILE_SIZE_LIMIT);

        List<FileItem> items = fileUpload.parseRequest(request);

        for (FileItem item : items) {
            if (item.isFormField()) {
                logger.info("Received form field");

                logger.info("Name: " + item.getFieldName());

                logger.info("Value: " + item.getString());
            } else {
                logger.info("Received file");

                logger.info("Name: " + item.getName());

                logger.info("Size: " + item.getSize());
            }
            if (false == item.isFormField()) {
                if (item.getSize() > FILE_SIZE_LIMIT) {
                    response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
                            "File size exceeds limit");

                    return;
                }
                // Typically here you would process the file in some way:
                // InputStream in = item.getInputStream();
                // ...

                if (false == item.isInMemory()) {
                    item.delete();
                }
            }
        }
    } catch (Exception e) {
        logger.error("Throwing servlet exception for unhandled exception", e);

        throw new ServletException(e);
    }
}

From source file:de.htwg_konstanz.ebus.wholesaler.demo.workclasses.Upload.java

/**
 * Receives the XML File and generates an InputStream.
 *
 * @param request HttpServletRequest/*w w  w  .j  ava 2s  .  co m*/
 * @return InputStream Stream of the uploaded file
 * @throws FileUploadException Exception Handling for File Upload
 * @throws IOException Exception Handling for IO Exceptions
 */
public InputStream upload(final HttpServletRequest request) throws FileUploadException, IOException {
    // Check Variable to check if it is a File Uploade
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        //Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        //Console Out Starting the Upload progress.
        System.out.println("\n - - - UPLOAD");

        // List of all uploaded Files
        List files = upload.parseRequest(request);

        // Returns the uploaded File
        Iterator iter = files.iterator();

        FileItem element = (FileItem) iter.next();
        String fileName = element.getName();
        String extension = FilenameUtils.getExtension(element.getName());

        // check if file extension is xml, when not then it will be aborted
        if (!extension.equals("xml")) {
            return null;
        }

        System.out.println("Extension:" + extension);

        System.out.println("\nFilename: " + fileName);

        // Escaping Special Chars
        fileName = fileName.replace('/', '\\');
        fileName = fileName.substring(fileName.lastIndexOf('\\') + 1);

        // Converts the File into an Input Strem
        InputStream is;
        is = element.getInputStream();

        return is;
    }
    return null;
}

From source file:com.twinsoft.convertigo.engine.admin.services.UploadService.java

protected void getServiceResult(HttpServletRequest request, Document document) throws Exception {
    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (!isMultipart)
        throw new IllegalArgumentException("Not multipart content!");

    FileItemFactory factory = new DiskFileItemFactory();

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

    // Parse the request
    List<FileItem> items = GenericUtils.cast(upload.parseRequest(request));

    // Process the uploaded items
    handleFormFields(request);/*  ww w.j  av  a 2s .com*/
    for (FileItem item : items) {
        doUpload(request, document, item);
    }
}

From source file:Index.UploadFileServlet.java

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

    String ubicacionArchivo = "C:\\Users\\Romina\\Documents\\NetBeansProjects\\QuickOrderWeb\\web\\images";

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1024);
    factory.setRepository(new File(ubicacionArchivo));

    ServletFileUpload upload = new ServletFileUpload(factory);

    try {
        List<FileItem> partes = upload.parseRequest(request);

        for (FileItem item : partes) {
            File file = new File(ubicacionArchivo,
                    request.getSession().getAttribute("userName").toString() + ".jpg");
            item.write(file);
            System.out.println("name: " + item.getName());
        }
        request.setAttribute("error", null);
        request.setAttribute("result", "Se ha registrado correctamente");
        request.setAttribute("funcionalidad", "Imagen");
        request.getSession().removeAttribute("userName");

        request.getRequestDispatcher("/Login.jsp").forward(request, response);
    } catch (FileUploadException ex) {
        System.out.println("Error al subir el archivo: " + ex.getMessage());

        request.setAttribute("error", "Error al subir la imagen");
        request.setAttribute("funcionalidad", "Imagen");

        request.getRequestDispatcher("/Login.jsp").forward(request, response);
    } catch (Exception ex) {
        System.out.println("Error al subir el archivo: " + ex.getMessage());
        request.setAttribute("error", "Error al subir la imagen");
        request.setAttribute("funcionalidad", "Imagen");

        request.getRequestDispatcher("/Login.jsp").forward(request, response);

    }

}