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

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

Introduction

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

Prototype

String getFieldName();

Source Link

Document

Returns the name of the field in the multipart form corresponding to this file item.

Usage

From source file:com.larasolution.serverlts.FileUploadHandler.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //     tablename=request.getParameter(tablename)
    //process only if its multipart content
    FileOutputStream fos = new FileOutputStream("C:\\uploads\\data.csv");
    String list = "";
    List<List> allData = new ArrayList<List>();

    List<String> parameters = new ArrayList<String>();
    if (ServletFileUpload.isMultipartContent(request)) {

        try {//from   w ww.  j  a  va 2 s.  c o m

            StringBuilder data = new StringBuilder();
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            System.out.println(multiparts);
            for (FileItem item : multiparts) {
                if (item.isFormField()) {
                    parameters.add(item.getFieldName());
                    System.out.println(parameters);
                }
                if (!item.isFormField()) {
                    String name = new File(item.getName()).getName();

                    item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
                    //System.out.println(File.separator);
                    // Get the workbook object for XLSX file
                    XSSFWorkbook wBook = new XSSFWorkbook(
                            new FileInputStream(UPLOAD_DIRECTORY + File.separator + name));

                    XSSFSheet zz = wBook.getSheetAt(0);
                    FormulaEvaluator formulaEval = wBook.getCreationHelper().createFormulaEvaluator();

                    Row row;
                    Cell cell;

                    // Iterate through each rows from first sheet
                    Iterator<Row> rowIterator = zz.iterator();
                    while (rowIterator.hasNext()) {
                        row = rowIterator.next();

                        // For each row, iterate through each columns
                        Iterator<Cell> cellIterator = row.cellIterator();

                        while (cellIterator.hasNext()) {

                            cell = cellIterator.next();

                            switch (cell.getCellType()) {
                            case Cell.CELL_TYPE_BOOLEAN:
                                data.append(cell.getBooleanCellValue()).append(",");
                                break;
                            case Cell.CELL_TYPE_NUMERIC:
                                if (DateUtil.isCellDateFormatted(cell)) {
                                    data.append(
                                            com.larasolution.modle.getDate.getDate5(cell.getDateCellValue()))
                                            .append(",");
                                } else {
                                    data.append(cell.getNumericCellValue()).append(",");
                                }

                                break;
                            case Cell.CELL_TYPE_STRING:
                                data.append(cell.getStringCellValue()).append(",");
                                break;
                            case Cell.CELL_TYPE_BLANK:
                                data.append("" + ",");
                                break;
                            case Cell.CELL_TYPE_FORMULA:
                                Double value = Double.parseDouble(formulaEval.evaluate(cell).formatAsString());

                                data.append(String.format("%.2f", value)).append(",");
                                break;
                            default:
                                data.append(cell).append("");

                            }

                        }
                        data.append("\r\n");
                        //String k = data.substring(0, data.length() - 3);
                        //ls.add(k);

                        // data.setLength(0);
                    }

                    fos.write(data.toString().getBytes());
                    fos.close();

                    //
                }
            }

            savetosql();
            request.setAttribute("message", "successfully uploaded ");
        } catch (Exception ex) {
            request.setAttribute("message", "File Upload Failed due to " + ex);
        }

    } else {
        request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }

    request.setAttribute("arrayfile", allData);
    request.setAttribute("names", parameters);
    RequestDispatcher disp = getServletContext().getRequestDispatcher("/FileUploadResult.jsp");
    disp.forward(request, response);

    // System.out.println(allData.size());
    // response.sendRedirect("send.jsp?arrayfile=" + list + "");
    //request.getRequestDispatcher("/send.jsp?arrayfile='"+ls+"'").forward(request, response);
}

From source file:mx.org.cedn.avisosconagua.engine.processors.Init.java

/**
 * Processes an uploaded file and stores it in MongoDB.
 * @param item file item from the parsed servlet request
 * @param currentId ID for the current MongoDB object for the advice
 * @return file name/*from   w  ww .  j a va 2 s. c  o m*/
 * @throws IOException 
 */
private String processUploadedFile(FileItem item, String currentId) throws IOException {
    System.out.println("file: size=" + item.getSize() + " name:" + item.getName());
    GridFS gridfs = mi.getImagesFS();
    String filename = currentId + ":" + item.getFieldName() + "_" + item.getName();
    gridfs.remove(filename);
    GridFSInputFile gfsFile = gridfs.createFile(item.getInputStream());
    gfsFile.setFilename(filename);
    gfsFile.setContentType(item.getContentType());
    gfsFile.save();
    return filename;
}

From source file:calliope.handler.put.AesePutHandler.java

private void parseRequest(HttpServletRequest request) throws AeseException {
    try {// www .  ja v  a 2 s  .  c  o  m
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // Parse the request
        List items = upload.parseRequest(request);
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                if (fieldName != null) {
                    String contents = item.getString();
                    if (fieldName.equals(Params.STRIPPER))
                        stripperName = contents;
                    else if (fieldName.equals(Params.ENCODING))
                        encoding = contents;
                    else if (fieldName.equals(Params.STYLE))
                        style = contents;
                    else if (fieldName.equals(Params.TITLE))
                        title = contents;
                    else if (fieldName.equals(Params.VERSION1))
                        version1 = contents;
                    else if (fieldName.equals(Params.AUTHOR))
                        author = contents;
                    else if (fieldName.equals(Params.DESCRIPTION))
                        description = contents;
                }
            } else if (item.getName().length() > 0) {
                byte[] rawData = item.get();
                guessEncoding(rawData);
                if (encoding == null)
                    encoding = guessEncoding(rawData);
                fileContent = new String(rawData, encoding);
            }
        }
    } catch (Exception e) {
        throw new AeseException(e);
    }
}

From source file:Com.Dispatcher.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from  ww  w.ja  va2 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 doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    File file;

    Boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
        return;
    }

    // Create a session object if it is already not  created.
    HttpSession session = request.getSession(true);
    // Get session creation time.
    Date createTime = new Date(session.getCreationTime());
    // Get last access time of this web page.
    Date lastAccessTime = new Date(session.getLastAccessedTime());

    String visitCountKey = new String("visitCount");
    String userIDKey = new String("userID");
    String userID = new String("ABCD");
    Integer visitCount = (Integer) session.getAttribute(visitCountKey);

    // Check if this is new comer on your web page.
    if (visitCount == null) {

        session.setAttribute(userIDKey, userID);
    } else {

        visitCount++;
        userID = (String) session.getAttribute(userIDKey);
    }
    session.setAttribute(visitCountKey, visitCount);

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File(fileRepository));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        // Parse the request to get file items
        List fileItems = upload.parseRequest(request);
        // Process the uploaded file items
        Iterator i = fileItems.iterator();
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file to server in "/uploads/{sessionID}/"   
                String clientDataPath = getServletContext().getInitParameter("clientFolder");
                // TODO clear the client folder here
                // FileUtils.deleteDirectory(new File("clientDataPath"));
                if (fileName.lastIndexOf("\\") >= 0) {

                    File input = new File(clientDataPath + session.getId() + "/input/");
                    input.mkdirs();
                    File output = new File(clientDataPath + session.getId() + "/output/");
                    output.mkdirs();
                    session.setAttribute("inputFolder", clientDataPath + session.getId() + "/input/");
                    session.setAttribute("outputFolder", clientDataPath + session.getId() + "/output/");

                    file = new File(
                            input.getAbsolutePath() + "/" + fileName.substring(fileName.lastIndexOf("/")));
                } else {
                    File input = new File(clientDataPath + session.getId() + "/input/");
                    input.mkdirs();
                    File output = new File(clientDataPath + session.getId() + "/output/");
                    output.mkdirs();
                    session.setAttribute("inputFolder", clientDataPath + session.getId() + "/input/");
                    session.setAttribute("outputFolder", clientDataPath + session.getId() + "/output/");

                    file = new File(
                            input.getAbsolutePath() + "/" + fileName.substring(fileName.lastIndexOf("/") + 1));
                }
                fi.write(file);
            }
        }
    } catch (Exception ex) {
        System.out.println("Failure: File Upload");
        System.out.println(ex);
        //TODO show error page for website
    }
    System.out.println("file uploaded");
    // TODO make the fileRepository Folder generic so it doesnt need to be changed
    // for each migration of the program to a different server
    File input = new File((String) session.getAttribute("inputFolder"));
    File output = new File((String) session.getAttribute("outputFolder"));
    File profile = new File(getServletContext().getInitParameter("profileFolder"));
    File hintsXML = new File(getServletContext().getInitParameter("hintsXML"));

    System.out.println("folders created");

    Controller controller = new Controller(input, output, profile, hintsXML);
    HashMap initialArtifacts = controller.initialArtifacts();
    session.setAttribute("Controller", controller);

    System.out.println("Initialisation of profiles for session (" + session.getId() + ") is complete\n"
            + "Awaiting user to update parameters to generate next generation of results.\n");

    String json = new Gson().toJson(initialArtifacts);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

From source file:com.krawler.br.spring.RConverterImpl.java

public Map convertWithFile(HttpServletRequest request, Map reqParams) throws ProcessException {
    HashMap itemMap = new HashMap(), tmpMap = new HashMap();
    try {/*from   w  w w. ja  va  2 s .co m*/
        FileItemFactory factory = new DiskFileItemFactory(4096, new File("/tmp"));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(1000000);
        List fileItems = upload.parseRequest(request);
        Iterator iter = fileItems.iterator();

        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            String key = item.getFieldName();
            OperationParameter o = (OperationParameter) reqParams.get(key);
            if (reqParams.containsKey(key)) {
                if (item.isFormField()) {
                    putItem(tmpMap, key,
                            getValue(item.getString("UTF-8"), mb.getModuleDefinition(o.getType())));
                } else {
                    File destDir = new File(StorageHandler.GetProfileImgStorePath());
                    if (!destDir.exists()) {
                        destDir.mkdirs();
                    }

                    File f = new File(destDir, UUID.randomUUID() + "_" + item.getName());
                    try {
                        item.write(f);
                    } catch (Exception ex) {
                        Logger.getLogger(RConverterImpl.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    putItem(tmpMap, key, f.getAbsolutePath());
                }
            }
        }

        iter = tmpMap.keySet().iterator();

        while (iter.hasNext()) {
            String key = (String) iter.next();
            OperationParameter o = (OperationParameter) reqParams.get(key);
            itemMap.put(key, convertToMultiType((List) tmpMap.get(key), o.getMulti(), o.getType()));
        }

    } catch (FileUploadException ex) {
        throw new ProcessException(ex.getMessage(), ex);
    } catch (UnsupportedEncodingException e) {
        throw new ProcessException(e.getMessage(), e);
    }
    return itemMap;
}

From source file:edu.fullerton.ldvservlet.Upload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/*from ww w.ja va 2  s  . c  o  m*/
 * @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 {
    long startTime = System.currentTimeMillis();

    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("This action requires a multipart form with a file attached.");
    }
    ServletSupport servletSupport;

    servletSupport = new ServletSupport();
    servletSupport.init(request, viewerConfig, false);

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

    // Configure a repository (to ensure a secure temp location is used)
    ServletContext servletContext = this.getServletConfig().getServletContext();
    File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    factory.setRepository(repository);

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

    ImageTable imageTable;
    String viewServletPath = request.getContextPath() + "/view";

    try {
        imageTable = new ImageTable(servletSupport.getDb());
    } catch (SQLException ex) {
        String ermsg = "Image upload: can't access the Image table: " + ex.getClass().getSimpleName() + " "
                + ex.getLocalizedMessage();
        throw new ServletException(ermsg);
    }
    try {
        HashMap<String, String> params = new HashMap<>();
        ArrayList<Integer> uploadedIds = new ArrayList<>();

        Page vpage = servletSupport.getVpage();
        vpage.setTitle("Image upload");
        try {
            servletSupport.addStandardHeader(version);
            servletSupport.addNavBar();
        } catch (WebUtilException ex) {
            throw new ServerException("Adding nav bar after upload", ex);
        }

        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        int cnt = items.size();
        for (FileItem item : items) {
            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString();
                if (!value.isEmpty()) {
                    params.put(name, value);
                }
            }
        }
        for (FileItem item : items) {
            if (!item.isFormField()) {
                int imgId = addFile(item, params, vpage, servletSupport.getVuser().getCn(), imageTable);
                if (imgId != 0) {
                    uploadedIds.add(imgId);
                }
            }
        }
        if (!uploadedIds.isEmpty()) {
            showImages(vpage, uploadedIds, imageTable, viewServletPath);
        }
        servletSupport.showPage(response);
    } catch (FileUploadException ex) {
        Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:bijian.util.upload.MyMultiPartRequest.java

private void processUpload(HttpServletRequest request, String saveDir)
        throws FileUploadException, UnsupportedEncodingException {
    for (FileItem item : parseRequest(request, saveDir)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Found item " + item.getFieldName());
        }/*from  w w w .j  av a  2 s.c o  m*/
        if (item.isFormField()) {
            processNormalFormField(item, request.getCharacterEncoding());
        } else {
            processFileField(item);
        }
    }
}

From source file:com.ikon.servlet.admin.ReportServlet.java

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = "";
    String userId = request.getRemoteUser();
    updateSessionManager(request);//from  ww w .  j ava  2 s .c o m

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            InputStream is = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            Report rp = new Report();

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("action")) {
                        action = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("rp_id")) {
                        rp.setId(Integer.parseInt(item.getString("UTF-8")));
                    } else if (item.getFieldName().equals("rp_name")) {
                        rp.setName(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("rp_active")) {
                        rp.setActive(true);
                    }
                } else {
                    is = item.getInputStream();
                    rp.setFileName(FilenameUtils.getName(item.getName()));
                    rp.setFileMime(MimeTypeConfig.mimeTypes.getContentType(item.getName()));
                    rp.setFileContent(SecureStore.b64Encode(IOUtils.toByteArray(is)));
                    is.close();
                }
            }

            if (action.equals("create")) {
                long id = ReportDAO.create(rp);

                // Activity log
                UserActivity.log(userId, "ADMIN_REPORT_CREATE", Long.toString(id), null, rp.toString());
                list(userId, request, response);
            } else if (action.equals("edit")) {
                Report tmp = ReportDAO.findByPk(rp.getId());
                tmp.setActive(rp.isActive());
                tmp.setFileContent(rp.getFileContent());
                tmp.setFileMime(rp.getFileMime());
                tmp.setFileName(rp.getFileName());
                tmp.setName(rp.getName());
                ReportDAO.update(tmp);

                // Activity log
                UserActivity.log(userId, "ADMIN_REPORT_EDIT", Long.toString(rp.getId()), null, rp.toString());
                list(userId, request, response);
            } else if (action.equals("delete")) {
                ReportDAO.delete(rp.getId());

                // Activity log
                UserActivity.log(userId, "ADMIN_REPORT_DELETE", Long.toString(rp.getId()), null, null);
                list(userId, request, response);
            }
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    }
}

From source file:gov.nih.nci.caarray.web.fileupload.MonitoredMultiPartRequest.java

private void handleFormField(HttpServletRequest servletRequest, FileItem item)
        throws UnsupportedEncodingException {
    LOG.debug("Item is a normal form field");
    List<String> values = params.get(item.getFieldName());
    if (values == null) {
        values = new ArrayList<String>();
        params.put(item.getFieldName(), values);
    }/*from w w  w. j  a v  a 2 s  . com*/
    String charset = servletRequest.getCharacterEncoding();
    values.add(charset != null ? item.getString(charset) : item.getString());
}

From source file:crds.pub.FCKeditor.uploader.SimpleUploaderServlet.java

/**
 * Manage the Upload requests.<br>
 *
 * The servlet accepts commands sent in the following format:<br>
 * simpleUploader?Type=ResourceType<br><br>
 * It store the file (renaming it in case a file with the same name exists) and then return an HTML file
 * with a javascript command in it.//from  w  w w  . j a v  a2s.c  om
 *
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession();
    FormUserOperation formUser = Constant.getFormUserOperation(request);
    String fck_task_id = (String) request.getSession().getAttribute("fck_task_id");
    if (fck_task_id == null) {
        fck_task_id = "temp_task_id";
    }

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

    String typeStr = request.getParameter("Type");

    String currentPath = baseDir + formUser.getCompany_code() + "/" + fck_task_id + "/" + typeStr;
    String currentDirPath = getServletContext().getRealPath(currentPath);

    File currentDir = new File(currentDirPath);
    if (!currentDir.exists()) {
        currentDir.mkdirs();
    }

    String retVal = "0";
    String newName = "";
    String fileUrl = "";
    String errorMessage = "";

    if (enabled) {
        org.apache.commons.fileupload.DiskFileUpload upload = new org.apache.commons.fileupload.DiskFileUpload();
        try {
            List items = upload.parseRequest(request);

            Map fields = new HashMap();

            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField())
                    fields.put(item.getFieldName(), item.getString());
                else
                    fields.put(item.getFieldName(), item);
            }
            FileItem uplFile = (FileItem) fields.get("NewFile");
            String fileNameLong = uplFile.getName();
            fileNameLong = fileNameLong.replace('\\', '/');

            String[] pathParts = fileNameLong.split("/");
            String fileName = pathParts[pathParts.length - 1];

            String nameWithoutExt = getNameWithoutExtension(fileName);
            String ext = getExtension(fileName);
            File pathToSave = new File(currentDirPath, fileName);

            //???IP
            String server_ip = (String) session.getAttribute("server_ip");
            if (server_ip == null) {
                server_ip = CommonMethod.getServerIP(request) + ":" + request.getServerPort();//???IP?
            }
            String url = "http://" + server_ip + currentPath.substring(2, currentPath.length());

            fileUrl = url + "/" + fileName;
            if (extIsAllowed(typeStr, ext)) {
                int counter = 1;
                while (pathToSave.exists()) {
                    newName = nameWithoutExt + "(" + counter + ")" + "." + ext;
                    fileUrl = url + "/" + newName;
                    retVal = "201";
                    pathToSave = new File(currentDirPath, newName);
                    counter++;
                }
                uplFile.write(pathToSave);
            } else {
                retVal = "202";
                errorMessage = "";
            }
        } catch (Exception ex) {
            if (debug)
                ex.printStackTrace();
            retVal = "203";
        }
    } else {
        retVal = "1";
        errorMessage = "This file uploader is disabled. Please check the WEB-INF/web.xml file";
    }

    out.println("<script type=\"text/javascript\">");
    out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + fileUrl + "','" + newName + "','"
            + errorMessage + "');");
    out.println("</script>");
    out.flush();
    out.close();

}