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

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

Introduction

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

Prototype

public List  parseRequest(HttpServletRequest request) throws FileUploadException 

Source Link

Document

Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a> compliant <code>multipart/form-data</code> stream.

Usage

From source file:controladoresAdministrador.ControladorCargarInicial.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   ww 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.redoute.datamap.servlet.picture.AddPicture.java

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

    String page = "";
    String application = "";
    String pictureName = "";
    String screenshot = "";
    FileItem item = null;//from ww  w .  j a v a2  s  .  c  om

    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {

            String fileName = null;
            List items = upload.parseRequest(request);
            List items2 = items;
            Iterator iterator = items.iterator();
            Iterator iterator2 = items2.iterator();
            File uploadedFile = null;
            String idNC = "";

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

                if (item.isFormField()) {
                    String name = item.getFieldName();
                    if (name.equals("Page")) {
                        page = item.getString("UTF-8");
                        System.out.println(page);
                    }
                    if (name.equals("Application")) {
                        application = item.getString("UTF-8");
                        System.out.println(application);
                    }
                    if (name.equals("PictureName")) {
                        pictureName = item.getString("UTF-8");
                        System.out.println(pictureName);
                    }
                    if (name.equals("Screenshot")) {
                        screenshot = item.getString().split("<img src=\"")[1].split("\">")[0];
                        System.out.println(screenshot);
                        System.out.println(screenshot.length());
                    }
                }
            }

            ApplicationContext appContext = WebApplicationContextUtils
                    .getWebApplicationContext(this.getServletContext());
            IPictureService pictService = appContext.getBean(IPictureService.class);
            IFactoryPicture factoryPicture = appContext.getBean(IFactoryPicture.class);

            Picture pict = factoryPicture.create(0, application, page, pictureName, screenshot);
            pictService.createPicture(pict);

            response.sendRedirect("Datamap.jsp");
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

From source file:hoot.services.ingest.MultipartSerializer.java

/**
 * Serializes uploaded multipart data into files. It can handle file or folder type.
 * //from w w  w.  j a  v  a 2 s .c  o  m
 * @param jobId = unique id to identify uploaded files group
 * @param inputType = ["FILE" | "DIR"] where DIR type is treated as FGDB
 * @param uploadedFiles = The list of files uploaded
 * @param uploadedFilesPaths = The list of uploaded files paths
 * @param request = The request object that holds post data
 * @throws Exception
 */
public void serializeUpload(final String jobId, String inputType, Map<String, String> uploadedFiles,
        Map<String, String> uploadedFilesPaths, final HttpServletRequest request) throws Exception {
    // Uploaded data container folder path. It is unique to each job
    String repFolderPath = homeFolder + "/upload/" + jobId;
    File dir = new File(repFolderPath);
    FileUtils.forceMkdir(dir);

    if (!ServletFileUpload.isMultipartContent(request)) {
        ResourceErrorHandler.handleError("Content type is not multipart/form-data", Status.BAD_REQUEST, log);
    }
    DiskFileItemFactory fileFactory = new DiskFileItemFactory();
    File filesDir = new File(repFolderPath);
    fileFactory.setRepository(filesDir);
    ServletFileUpload uploader = new ServletFileUpload(fileFactory);

    List<FileItem> fileItemsList = uploader.parseRequest(request);
    Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();

    // If user request type is DIR then treat it as FGDB folder
    if (inputType.equalsIgnoreCase("DIR")) {
        _serializeFGDB(fileItemsList, jobId, uploadedFiles, uploadedFilesPaths);

    } else {
        // Can be shapefile or zip file
        _serializeUploadedFiles(fileItemsList, jobId, uploadedFiles, uploadedFilesPaths, repFolderPath);
    }
}

From source file:com.controller.ChangeImageServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/*from w  w w .  j av  a  2  s . c  om*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    // process only if it is multipart content
    String path = "";
    if (isMultipart) {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            // Parse the request
            List<FileItem> multiparts = upload.parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String name = new File(item.getName()).getName();
                    item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
                    path = UPLOAD_DIRECTORY + File.separator + name;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    response.setContentType("text/plain");
    response.getWriter().write(path);
}

From source file:com.king.platform.net.http.integration.MultiPart.java

@Test
public void postMultiPart() throws Exception {

    AtomicReference<List<FileItem>> partReferences = new AtomicReference<>();
    AtomicReference<Exception> exceptionReference = new AtomicReference<>();

    integrationServer.addServlet(new HttpServlet() {
        @Override/*from w  w  w .j  a  v a 2 s .co m*/
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());

            try {
                List<FileItem> fileItems = servletFileUpload.parseRequest(req);
                partReferences.set(fileItems);
            } catch (FileUploadException e) {
                exceptionReference.set(e);
            }

        }
    }, "/testMultiPart");

    httpClient
            .createPost(
                    "http://localhost:" + port + "/testMultiPart")
            .idleTimeoutMillis(
                    0)
            .totalRequestTimeoutMillis(
                    0)
            .content(
                    new MultiPartBuilder()
                            .addPart(
                                    MultiPartBuilder
                                            .create("text1", "Message 1",
                                                    StandardCharsets.ISO_8859_1)
                                            .contentType("multipart/form-data"))
                            .addPart(MultiPartBuilder.create("binary1", new byte[] { 0x00, 0x01, 0x02 })
                                    .contentType("application/octet-stream").charset(StandardCharsets.UTF_8)
                                    .fileName("application.bin"))
                            .addPart(MultiPartBuilder.create("text2", "Message 2", StandardCharsets.ISO_8859_1))
                            .build())
            .build().execute().join();

    assertNull(exceptionReference.get());

    List<FileItem> fileItems = partReferences.get();
    FileItem fileItem = fileItems.get(1);
    assertEquals("application/octet-stream; charset=UTF-8", fileItem.getContentType());
    assertEquals("binary1", fileItem.getFieldName());
    assertEquals("application.bin", fileItem.getName());

}

From source file:edu.lafayette.metadb.web.dataman.ImportAdminDesc.java

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*///from w  ww  .  ja va2  s . co m

@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    PrintWriter out = response.getWriter();
    String delimiter = "comma";
    boolean replaceEntity = false;
    String projname = (String) request.getSession(false).getAttribute(Global.SESSION_PROJECT);
    JSONObject output = new JSONObject();

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
            List fileItemsList = servletFileUpload.parseRequest(request);
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setSizeThreshold(40960); /* the unit is bytes */

            Iterator it = fileItemsList.iterator();
            InputStream input = null;
            while (it.hasNext()) {
                FileItem fileItem = (FileItem) it.next();

                if (fileItem.isFormField()) {
                    /* The file item contains a simple name-value pair of a form field */
                    if (fileItem.getFieldName().equals("delimiter"))
                        delimiter = fileItem.getString();
                    else if (fileItem.getFieldName().equals("replace-entity"))
                        replaceEntity = true;
                } else {
                    input = fileItem.getInputStream();
                }
            }

            String delimiterType = "csv";
            if (delimiter.equals("tab")) {
                delimiterType = "tsv";
            }
            if (input != null) {
                Result res = DataImporter.importFile(delimiterType, projname, input, replaceEntity);
                if (res.isSuccess()) {
                    HttpSession session = request.getSession(false);
                    if (session != null) {
                        String userName = (String) session.getAttribute(Global.SESSION_USERNAME);
                        SysLogDAO.log(userName, Global.SYSLOG_PROJECT,
                                "Data imported into project " + projname);
                    }
                    output.put("message", "Data import successfully");
                } else {
                    output.put("message", "The following fields have been changed:");
                    StringBuilder fields = new StringBuilder();
                    for (String field : (ArrayList<String>) res.getData())
                        fields.append(field + ',');
                    output.put("fields", fields.toString());
                }
                output.put("success", res.isSuccess());
            } else {
                output.put("success", false);
                output.put("message", "Null data");
            }
        } else {
            output.put("success", false);
            output.put("message", "Form is not multi-part");
        }
    } catch (Exception e) {
        MetaDbHelper.logEvent(e);
    }
    out.print(output);
    out.flush();
}

From source file:com.lock.unlockInfo.servlet.SubmitUnlockImg.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpResponseModel responseModel = new HttpResponseModel();
    try {/*  w  w w  . jav  a  2s  . c o  m*/
        boolean isMultipart = ServletFileUpload.isMultipartContent(request); // ???
        if (isMultipart) {
            Hashtable<String, String> htSubmitParam = new Hashtable<String, String>(); // ??
            List<String> fileList = new ArrayList<String>();// 

            // DiskFileItemFactory??
            // ????List
            // list???
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            Iterator<FileItem> iterator = items.iterator();
            while (iterator.hasNext()) {
                FileItem item = iterator.next();
                if (item.isFormField()) {
                    // ?
                    String sFieldName = item.getFieldName();
                    String sFieldValue = item.getString("UTF-8");
                    htSubmitParam.put(sFieldName, sFieldValue);
                } else {
                    // ,???
                    String newFileName = System.currentTimeMillis() + "_" + UUID.randomUUID().toString()
                            + ".jpg";
                    File filePath = new File(
                            getServletConfig().getServletContext().getRealPath(Constants.File_Upload));
                    if (!filePath.exists()) {
                        filePath.mkdirs();
                    }
                    File file = new File(filePath, newFileName);
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    //?
                    BufferedInputStream bis = new BufferedInputStream(item.getInputStream());
                    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                    byte[] b = new byte[1024];
                    int length = 0;
                    while ((length = bis.read(b)) > 0) {
                        bos.write(b, 0, length);
                    }
                    bos.close();
                    bis.close();
                    //?url
                    String fileUrl = request.getRequestURL().toString();
                    fileUrl = fileUrl.substring(0, fileUrl.lastIndexOf("/")); //?URL
                    fileUrl = fileUrl + Constants.File_Upload + "/" + newFileName;
                    /**/
                    fileList.add(fileUrl);
                }
            }

            //
            String unlockInfoId = htSubmitParam.get("UnlockInfoId");
            String imgType = htSubmitParam.get("ImgType");
            String newFileUrl = fileList.get(0);

            UnlockInfoService unlockInfoService = (UnlockInfoService) context.getBean("unlockInfoService");
            UnlockInfo unlockInfo = unlockInfoService.queryByPK(Long.valueOf(unlockInfoId));
            if (imgType.equals("customerIdImg")) {
                unlockInfo.setCustomerIdImg(newFileUrl);
            } else if (imgType.equals("customerDrivingLicenseImg")) {
                unlockInfo.setCustomerDrivingLicenseImg(newFileUrl);
            } else if (imgType.equals("customerVehicleLicenseImg")) {
                unlockInfo.setCustomerVehicleLicenseImg(newFileUrl);
            } else if (imgType.equals("customerBusinessLicenseImg")) {
                unlockInfo.setCustomerBusinessLicenseImg(newFileUrl);
            } else if (imgType.equals("customerIntroductionLetterImg")) {
                unlockInfo.setCustomerIntroductionLetterImg(newFileUrl);
            } else if (imgType.equals("unlockWorkOrderImg")) {
                unlockInfo.setUnlockWorkOrderImg(newFileUrl);
            }
            /**/
            unlockInfoService.update(unlockInfo);
        }
    } catch (Exception e) {
        e.printStackTrace();
        responseModel.responseCode = "0";
        responseModel.responseMessage = e.toString();
    }
    /* ??? */
    response.setHeader("content-type", "text/json;charset=utf-8");
    response.getOutputStream().write(responseModel.toByteArray());
}

From source file:Controller.ControllerImageCustomerIndex.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from  w w  w. j  av  a  2s.  co m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {

    } else {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Iterator iter = items.iterator();
        Hashtable params = new Hashtable();
        String fileName = null;
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), item.getString());
            } else {

                try {
                    String itemName = item.getName();
                    fileName = itemName.substring(itemName.lastIndexOf("\\") + 1);
                    System.out.println("path" + fileName);
                    String RealPath = getServletContext().getRealPath("/") + "upload\\" + fileName;
                    System.out.println("Rpath" + RealPath);
                    File savedFile = new File(RealPath);
                    item.write(savedFile);
                    String username = (String) params.get("txtusername");
                    String password = (String) params.get("txpassword");
                    String hoten = (String) params.get("txthoten");
                    String gioitinh = (String) params.get("txtgioitinh");
                    String email = (String) params.get("txtemail");
                    String role = "false";
                    Customer cus = new Customer(username, password, hoten, gioitinh, email, role,
                            "upload\\" + fileName);

                    CustomerDAO.ThemKhachHang(cus);
                    RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
                    rd.forward(request, response);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

    }

}

From source file:edu.iastate.airl.semtus.server.UploadServiceController.java

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {

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

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

        // Parse the request
        try {//from  w w w .j  ava 2s  .  c o  m
            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                // process only file upload - discard other form item types
                if (item.isFormField())
                    continue;

                String fileName = item.getName();
                // get only the file name not whole path
                if (fileName != null) {
                    fileName = FilenameUtils.getName(fileName);
                }

                File uploadedFile = new File(Utils.UPLOAD_DIRECTORY, fileName);

                // first clean-up the folder; we want no clutter on the server :-)
                String[] ls = new File(Utils.UPLOAD_DIRECTORY).list();

                for (int idx = 0; idx < ls.length; idx++) {

                    File file = new File(Utils.UPLOAD_DIRECTORY, ls[idx]);
                    file.delete();
                }

                if (uploadedFile.createNewFile()) {

                    item.write(uploadedFile);
                    resp.setStatus(HttpServletResponse.SC_CREATED);
                    resp.getWriter().print("The file was created successfully.");
                    resp.flushBuffer();

                } else {

                    throw new IOException("The file already exists in repository.");
                }
            }
        } catch (Exception e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while creating the file : " + e.getMessage());
        }

    } else {
        resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}

From source file:egovframework.com.utl.wed.filter.CkImageSaver.java

public void saveAndReturnUrlToClient(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    // Parse the request
    try {//from   w w w .  j ava 2s.c  o  m
        FileItemFactory factory = new DiskFileItemFactory();

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

        List<FileItem> /* FileItem */ items = upload.parseRequest(request);
        // We upload just one file at the same time
        FileItem uplFile = items.get(0);

        String errorMessage = null;
        String relUrl = null;

        if (isAllowFileType(FilenameUtils.getName(uplFile.getName()))) {
            relUrl = fileSaveManager.saveFile(uplFile, imageBaseDir, imageDomain);

        } else {
            errorMessage = "Restricted Image Format";
        }

        StringBuffer sb = new StringBuffer();
        sb.append("<script type=\"text/javascript\">\n");
        // Compressed version of the document.domain automatic fix script.
        // The original script can be found at [fckeditor_dir]/_dev/domain_fix_template.js
        // sb.append("(function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})();\n");
        sb.append("window.parent.CKEDITOR.tools.callFunction(").append(request.getParameter(FUNC_NO))
                .append(", '");
        sb.append(relUrl);
        if (errorMessage != null) {
            sb.append("', '").append(errorMessage);
        }
        sb.append("');\n </script>");

        response.setContentType("text/html");
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out = response.getWriter();

        out.print(sb.toString());
        out.flush();
        out.close();

    } catch (FileUploadException e) {
        log.error(e);
    }
}