Example usage for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload

Introduction

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

Prototype

public ServletFileUpload(FileItemFactory fileItemFactory) 

Source Link

Document

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

Usage

From source file:DatasetUpload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w  w w. j  ava  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");
    PrintWriter out = response.getWriter();
    try {

        //process only if its multipart content
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory())
                        .parseRequest(request);

                String DatasetName = "";
                for (FileItem item : multiparts) {
                    if (!item.isFormField()) {
                        DatasetName = new File(item.getName()).getName();
                        //write the file to disk
                        // item.write(new File(datasetFolder + File.separator + name));
                        //System.out.println("File name is :: " + name);  
                        // out.print("Upload successeful");
                    }
                }

                DatasetName = DatasetName.substring(0, DatasetName.indexOf("."));
                // System.out.println(DatasetName + "*****");

                String datasetFolderPath = getServletContext()
                        .getRealPath("datasets" + File.separator + DatasetName);

                File datasetFolder = new File(datasetFolderPath);

                //create the folder if it does not exist
                if (!datasetFolder.exists()) {
                    datasetFolder.mkdir();
                }

                for (FileItem item : multiparts) {
                    if (!item.isFormField()) {
                        String name = new File(item.getName()).getName();
                        //write the file to disk
                        item.write(new File(datasetFolder + File.separator + name));
                        //System.out.println("File name is :: " + name);  
                        out.print("Upload successeful");
                    }
                }
            } catch (Exception ex) {
                out.print("File Upload Failed due to " + ex);
            }
        } else {
            out.print("The request did not include any file");
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        out.close();
    }
}

From source file:controladoresAdministrador.ControladorCargarInicial.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w ww .  ja va2  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.github.davidcarboni.encryptedfileupload.FileUploadTestCase.java

protected List<FileItem> parseUpload(byte[] bytes, String contentType) throws FileUploadException {
    ServletFileUpload upload = new ServletFileUpload(new EncryptedFileItemFactory());
    HttpServletRequest request = new MockHttpServletRequest(bytes, contentType);

    List<FileItem> fileItems = upload.parseRequest(request);
    return fileItems;
}

From source file:com.adanac.module.blog.servlet.UploadImage.java

@Override
protected void service() throws ServletException, IOException {
    HttpServletRequest request = getRequest();
    String path = null;// w  w  w. j  a  va  2s.c o m
    DiskFileItemFactory factory = new DiskFileItemFactory(5 * 1024,
            new File(Configuration.getContextPath("temp")));
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(3 * 1024 * 1024);
    try {
        List<FileItem> items = upload.parseRequest(request);
        FileItem fileItem = null;
        if (items != null && items.size() > 0 && StringUtils.isNotBlank((fileItem = items.get(0)).getName())) {
            String fileName = fileItem.getName();
            if (!fileName.endsWith(".jpg") && !fileName.endsWith(".gif") && !fileName.endsWith(".png")) {
                writeText("format_error");
                return;
            }
            path = ImageUtil.generatePath(fileItem.getName());
            IOUtil.copy(fileItem.getInputStream(), Configuration.getContextPath(path));
            fileItem.delete();
            writeText(Configuration.getSiteUrl(path));
        }
    } catch (FileUploadException e) {
        throw new RuntimeException(e);
    }
}

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   www  .  j  a  v a  2  s. 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//from  w ww . ja  v  a  2s.c om
 * @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:controller.UpdateImage.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    HttpSession session = request.getSession();
    String manv = session.getAttribute("manv").toString();
    if (!ServletFileUpload.isMultipartContent(request)) {
        out.println("Nothing to upload");
        return;// w w w  . j  a  v a 2  s. c o m
    }
    FileItemFactory itemfactory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(itemfactory);
    String a = "";
    try {
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) {
            String myfolder = ("asset/Images/nhanvien") + "/";
            File uploadDir = new File(
                    "E:/Cng ngh phn m?m/? ?n/1996Shop/ShopOnline/web/asset/Images/nhanvien");
            File file = File.createTempFile("img", ".png", uploadDir);
            item.write(file);
            a = myfolder + file.getName();
            nv.setImage(a);
            usersDAO.updateImage(a, manv);
            response.sendRedirect("Profile.jsp?MaNV=" + manv + "");
        }

    } catch (FileUploadException e) {
        out.println("upload fail");
    } catch (Exception ex) {

    }
}

From source file:com.liferay.samplestruts.struts.action.UploadAction.java

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    FileItemFactory factory = new DiskFileItemFactory();

    ServletFileUpload upload = new ServletFileUpload(factory);

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

    Iterator<FileItem> itr = items.iterator();

    String itemName = StringPool.BLANK;

    while (itr.hasNext()) {
        FileItem item = itr.next();/*  w  w  w  .ja va 2s.  c om*/

        if (!item.isFormField()) {
            if (_log.isInfoEnabled()) {
                _log.info("Field name " + item.getFieldName());
            }

            itemName = item.getName();

            if (_log.isInfoEnabled()) {
                _log.info("Name " + itemName);
                _log.info("Content type " + item.getContentType());
                _log.info("In memory " + item.isInMemory());
                _log.info("Size " + item.getSize());
            }
        }
    }

    request.setAttribute("file_name", itemName);

    return mapping.findForward("/sample_struts_portlet/upload_success");
}

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  ww  w.j  av a2  s .  c  o 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:ju.ehealthservice.images.SaveImage.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w w w .ja v  a 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 {
    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();
    String ajaxUpdateResult = "";
    try {
        /* TODO output your page here. You may use following sample code. */
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
        List<FileItem> items = upload.parseRequest(request);
        String fileName = "";
        for (FileItem item : items) {
            if (item.isFormField()) {
                fileName = item.getString();
            } else {
                String filePath = Constants.IMAGE_REPOSITORY_PATH + fileName + ".jpg";
                File storeFile = new File(filePath);
                metadata.getData(fileName);
                metadata.updateImage(true);
                item.write(storeFile);
            }
        }
        ajaxUpdateResult = "true";
    } catch (FileUploadException ex) {
        ex.printStackTrace();
        ajaxUpdateResult = "false";
    } catch (Exception ex) {
        ex.printStackTrace();
        ajaxUpdateResult = "false";
    }
    out.print(ajaxUpdateResult);
}