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.arcadian.loginservlet.LecturesServlet.java

/**
 * Handles the HTTP/* www. j a  v  a 2  s  .  c o m*/
 * <code>POST</code> method.
 *
 * @param request servlet request
 * @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 {
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("Content type is not multipart/form-data");
    }
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    try {
        List<FileItem> fileItemsList = uploader.parseRequest(request);
        Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
        String lectureid = "";
        String lecturename = "";
        String subjectid = "";
        String classname = "";
        while (fileItemsIterator.hasNext()) {
            FileItem fileItem = fileItemsIterator.next();
            if (fileItem.isFormField()) {

                String name = fileItem.getFieldName();
                System.out.println(name);

                String value = fileItem.getString();
                System.out.println(value);

                if (name.equalsIgnoreCase("lectureid")) {
                    lectureid = value;
                }
                if (name.equalsIgnoreCase("lecturename")) {
                    lecturename = value;
                }
                if (name.equalsIgnoreCase("subjectid")) {
                    subjectid = value;
                }
                if (name.equalsIgnoreCase("semname")) {
                    classname = value;
                }

            }

            if (fileItem.getName() != null) {

                File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator
                        + fileItem.getName());
                System.out.println("Absolute Path at server=" + file.getAbsolutePath());
                fileItem.write(file);

                lecturesService = new LecturesService();
                lecturesService.updateLectures(lectureid, lecturename, classname, subjectid, username,
                        fileItem.getName());
            }
        }

    } catch (FileUploadException e) {
        System.out.println("Exception in file upload" + e);
    } catch (Exception ex) {
        Logger.getLogger(CourseContentServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    processRequest(request, response);
}

From source file:mml.handler.post.MMLPostHandler.java

/**
 * Parse the import params from the request
 * @param request the http request/*  w w w  .j  a  va2  s.co  m*/
 */
void parseImportParams(HttpServletRequest request) throws MMLException {
    try {
        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(this.encoding);
                    if (fieldName.equals(Params.DOCID)) {
                        int index = contents.lastIndexOf(".");
                        if (index != -1)
                            contents = contents.substring(0, index);
                        docid = contents;
                    } else if (fieldName.equals(Params.AUTHOR))
                        this.author = contents;
                    else if (fieldName.equals(Params.TITLE))
                        this.title = contents;
                    else if (fieldName.equals(Params.STYLE))
                        this.style = contents;
                    else if (fieldName.equals(Params.FORMAT))
                        this.format = contents;
                    else if (fieldName.equals(Params.SECTION))
                        this.section = contents;
                    else if (fieldName.equals(Params.VERSION1))
                        this.version1 = contents;
                    else if (fieldName.equals(Params.ENCODING))
                        encoding = contents;
                    else if (fieldName.equals(Params.ANNOTATIONS))
                        annotations = (JSONArray) JSONValue.parse(contents);
                }
            } else if (item.getName().length() > 0) {
                try {
                    // item.getName retrieves the ORIGINAL file name
                    String type = item.getContentType();
                    if (type != null) {
                        if (type.startsWith("image/")) {
                            InputStream is = item.getInputStream();
                            ByteHolder bh = new ByteHolder();
                            while (is.available() > 0) {
                                byte[] b = new byte[is.available()];
                                is.read(b);
                                bh.append(b);
                            }
                            ImageFile iFile = new ImageFile(item.getName(), item.getContentType(),
                                    bh.getData());
                            if (images == null)
                                images = new ArrayList<ImageFile>();
                            images.add(iFile);
                        } else if (type.equals("text/plain")) {
                            InputStream is = item.getInputStream();
                            ByteHolder bh = new ByteHolder();
                            while (is.available() > 0) {
                                byte[] b = new byte[is.available()];
                                is.read(b);
                                bh.append(b);
                            }
                            String style = new String(bh.getData(), encoding);
                            if (files == null)
                                files = new ArrayList<String>();
                            files.add(style);
                        }
                    }
                } catch (Exception e) {
                    throw new MMLException(e);
                }
            }
        }
    } catch (Exception e) {
        throw new MMLException(e);
    }
}

From source file:com.silverpeas.form.AbstractFormTest.java

@Test
public void testIsEmptyWithAllFileItemsWithoutContent() throws Exception {
    MyFormImpl myForm = new MyFormImpl(
            new MyRecordTemplate(new MyFieldTemplate(FIELD_NAME1, FIELD_TYPE, FIELD_LABEL1),
                    new MyFieldTemplate(FIELD_NAME2, FIELD_TYPE, FIELD_LABEL2)));
    DataRecord dataRecord = mock(DataRecord.class);
    PagesContext pagesContext = mock(PagesContext.class);
    FileItem fileItem1 = mock(FileItem.class);
    when(fileItem1.getFieldName()).thenReturn(FIELD_NAME1);
    when(fileItem1.getName()).thenReturn(FIELD_NAME1);
    when(fileItem1.isFormField()).thenReturn(true);
    when(fileItem1.getString(anyString())).thenReturn("");
    FileItem fileItem2 = mock(FileItem.class);
    when(fileItem2.getFieldName()).thenReturn(FIELD_NAME2);
    when(fileItem2.getName()).thenReturn(FIELD_NAME2);
    when(fileItem2.isFormField()).thenReturn(true);
    when(fileItem2.getString(anyString())).thenReturn(null);
    boolean isEmpty = myForm.isEmpty(Arrays.asList(fileItem1, fileItem2), dataRecord, pagesContext);
    assertTrue(isEmpty);//from  w w  w .  ja v  a  2 s . co  m
}

From source file:com.silverpeas.form.AbstractFormTest.java

@Test
public void testIsNotEmptyWithOnlyOneFileItemWithoutContent() throws Exception {
    MyFormImpl myForm = new MyFormImpl(
            new MyRecordTemplate(new MyFieldTemplate(FIELD_NAME1, FIELD_TYPE, FIELD_LABEL1),
                    new MyFieldTemplate(FIELD_NAME2, FIELD_TYPE, FIELD_LABEL2)));
    DataRecord dataRecord = mock(DataRecord.class);
    PagesContext pagesContext = mock(PagesContext.class);
    FileItem fileItem1 = mock(FileItem.class);
    when(fileItem1.getFieldName()).thenReturn(FIELD_NAME1);
    when(fileItem1.getName()).thenReturn(FIELD_NAME1);
    when(fileItem1.isFormField()).thenReturn(true);
    when(fileItem1.getString(anyString())).thenReturn("tartempion");
    FileItem fileItem2 = mock(FileItem.class);
    when(fileItem2.getFieldName()).thenReturn(FIELD_NAME2);
    when(fileItem2.getName()).thenReturn(FIELD_NAME2);
    when(fileItem2.isFormField()).thenReturn(true);
    when(fileItem2.getString(anyString())).thenReturn(null);
    boolean isEmpty = myForm.isEmpty(Arrays.asList(fileItem1, fileItem2), dataRecord, pagesContext);
    assertFalse(isEmpty);/*from  w  ww  .j a  v a 2s .  c o  m*/
}

From source file:edu.cudenver.bios.filesvc.resource.UploadResource.java

/**
 * Handle POST requests for file upload//w  ww  .  j ava2  s .c  om
 * @param entity entity body information (multi-part form encoded)
 */
@Post
public void upload(Representation entity) {
    if (entity != null) {
        if (MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {

            // The Apache FileUpload project parses HTTP requests which
            // conform to RFC 1867, "Form-based File Upload in HTML". That
            // is, if an HTTP request is submitted using the POST method,
            // and with a content type of "multipart/form-data", then
            // FileUpload can parse that request, and get all uploaded files
            // as FileItem.

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

            // 2 Create a new file upload handler based on the Restlet
            // FileUpload extension that will parse Restlet requests and
            // generates FileItems.
            RestletFileUpload upload = new RestletFileUpload(factory);
            List<FileItem> items;
            try {
                // 3. Request is parsed by the handler which generates a
                // list of FileItems
                items = upload.parseRequest(getRequest());

                // Process only the uploaded item called "fileToUpload" and
                // save it on disk
                boolean found = false;
                FileItem fi = null;
                for (final Iterator<FileItem> it = items.iterator(); it.hasNext() && !found;) {
                    fi = (FileItem) it.next();
                    if (fi.getFieldName().equals(FORM_TAG_FILE)) {
                        found = true;
                        break;
                    }
                }
                // Once handled, the content of the uploaded file is sent
                // back to the client.
                Representation rep = null;
                if (found) {
                    // Create a new representation based on disk file.
                    // The content is arbitrarily sent as plain text.
                    rep = new StringRepresentation(fi.getString(), MediaType.TEXT_HTML);
                    getResponse().setEntity(rep);
                    getResponse().setStatus(Status.SUCCESS_OK);
                } else {
                    rep = new StringRepresentation("No file data found", MediaType.TEXT_HTML);
                    getResponse().setEntity(rep);
                    getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
                }
            } catch (Exception e) {
                // The message of all thrown exception is sent back to
                // client as simple plain text
                getResponse().setEntity(
                        new StringRepresentation("Upload failed: " + e.getMessage(), MediaType.TEXT_HTML));
                getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
            }
        }
    } else {
        // POST request with no entity.
        getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
    }
}

From source file:Control.LoadImage.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//  w ww .jav a2 s . 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 {
    String tempPath = "/temp";
    String absoluteTempPath = this.getServletContext().getRealPath(tempPath);
    String absoluteFilePath = this.getServletContext().getRealPath("/data/Image");
    int maxFileSize = 50 * 1024;
    int maxMemSize = 4 * 1024;

    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(maxMemSize);
        File file = new File(absoluteTempPath);

        if (file == null) {
            // tao thu muc
        }

        factory.setRepository(file);
        ServletFileUpload upload = new ServletFileUpload(factory);

        //upload.setProgressListener(new MyProgressListener(out));
        List<FileItem> items = upload.parseRequest(request);

        if (items.size() > 0) {
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    if ("images".equals(item.getFieldName())) {
                        if (item.getName() != null && !item.getName().isEmpty()) {
                            String extension = null;
                            if (item.getName().endsWith("jpg")) {
                                String newLink = "/Image/" + Image.LengthListImg() + ".jpg";
                                file = new File(absoluteFilePath + "//" + Image.LengthListImg() + ".jpg");
                                // G?i hm add hnh vo database, link hnh l newLink
                                item.write(file);
                            } else if (item.getName().endsWith("png")) {
                                String newLink = "/Image/" + Image.LengthListImg() + ".png";
                                file = new File(absoluteFilePath + "//" + Image.LengthListImg() + ".png");
                                // G?i hm add hnh vo database, link hnh l newLink
                                item.write(file);
                            } else if (item.getName().endsWith("JPG")) {
                                String newLink = "/Image/" + Image.LengthListImg() + ".JPG";
                                file = new File(absoluteFilePath + "//" + Image.LengthListImg() + ".JPG");
                                // G?i hm add hnh vo database, link hnh l newLink
                                item.write(file);
                            } else if (item.getName().endsWith("PNG")) {
                                String newLink = "/Image/" + Image.LengthListImg() + ".PNG";
                                file = new File(absoluteFilePath + "//" + Image.LengthListImg() + ".PNG");
                                // G?i hm add hnh vo database, link hnh l newLink
                                item.write(file);
                            }
                        }
                    }
                } else {
                }
            }
            response.sendRedirect(request.getContextPath() + "/LoadImage.jsp");
            return;
        }

        List<Image> images = loadImages(request, response);

        request.setAttribute("images", images);
        request.setAttribute("error", "No file upload");
        RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/LoadImage.jsp");
        dispatcher.forward(request, response);
    } catch (Exception ex) {
        System.err.println(ex);
    }
}

From source file:edu.ucla.loni.server.Upload.java

public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    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);

        try {/*from  w  ww .  jav  a 2  s . c  o  m*/
            @SuppressWarnings("unchecked")
            List<FileItem> items = upload.parseRequest(req);

            // Go through the items and get the root and package
            String rootPath = "";
            String packageName = "";

            for (FileItem item : items) {
                if (item.isFormField()) {
                    if (item.getFieldName().equals("root")) {
                        rootPath = item.getString();
                    } else if (item.getFieldName().equals("packageName")) {
                        packageName = item.getString();
                    }
                }
            }

            if (rootPath.equals("")) {
                res.getWriter().println("error :: Root directory has not been found.");
                return;
            }

            Directory root = Database.selectDirectory(rootPath);

            // Go through items and process urls and files
            for (FileItem item : items) {
                // Uploaded File
                if (item.isFormField() == false) {
                    String filename = item.getName();
                    ;
                    if (filename.equals("") == true)
                        continue;
                    try {
                        InputStream in = item.getInputStream();
                        //determine if it is pipefile or zipfile
                        //if it is pipefile => feed directly to writeFile function
                        //otherwise, uncompresse it first and then one-by-one feed to writeFile
                        if (filename.endsWith(".zip")) {
                            ZipInputStream zip = new ZipInputStream(in);
                            ZipEntry entry = zip.getNextEntry();
                            while (entry != null) {
                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                if (baos != null) {
                                    byte[] arr = new byte[4096];
                                    int index = 0;
                                    while ((index = zip.read(arr, 0, 4096)) != -1) {
                                        baos.write(arr, 0, index);
                                    }
                                }
                                InputStream is = new ByteArrayInputStream(baos.toByteArray());
                                writeFile(root, packageName, is);
                                entry = zip.getNextEntry();
                            }
                            zip.close();
                        } else {
                            writeFile(root, packageName, in);

                        }

                        in.close();
                    } catch (Exception e) {
                        res.getWriter().println("Failed to upload " + filename + ". " + e.getMessage());
                    }
                }
                // URLs               
                if (item.isFormField() && item.getFieldName().equals("urls")
                        && item.getString().equals("") == false) {
                    String urlListAsStr = item.getString();
                    String[] urlList = urlListAsStr.split("\n");

                    for (String urlStr : urlList) {
                        try {
                            URL url = new URL(urlStr);
                            URLConnection urlc = url.openConnection();

                            InputStream in = urlc.getInputStream();

                            writeFile(root, packageName, in);

                            in.close();
                        } catch (Exception e) {
                            res.getWriter().println("Failed to upload " + urlStr);
                            return;
                        }
                    }
                }
            }
        } catch (Exception e) {
            res.getWriter().println("Error occurred while creating file. Error Message : " + e.getMessage());
        }
    }
}

From source file:Emporium.Servlet.ServPreVendaImportarNFe.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w w w .j av a2 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 {

    HttpSession sessao = request.getSession();
    String nomeBD = (String) sessao.getAttribute("nomeBD");

    boolean isMultiPart = FileUpload.isMultipartContent(request);

    String departamento = "", servico = "", tipo = "";
    int idCliente = 0, vd = 0, ar = 0, rm = 0, tipoEntrega = 0;

    if (nomeBD != null) {
        if (isMultiPart) {
            try {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setSizeMax(1024 * 1024 * 2);

                List items = upload.parseRequest(request);
                Iterator iter = items.iterator();
                ArrayList<FileItem> listaArq = new ArrayList<FileItem>();

                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (item.isFormField()) {
                        if (item.getFieldName().equals("tipo")) {
                            tipo = item.getString();
                        }
                        if (item.getFieldName().equals("departamento")) {
                            departamento = item.getString();
                        }
                        if (item.getFieldName().equals("servico")) {
                            servico = item.getString();
                        }
                        if (item.getFieldName().equals("idCliente")) {
                            idCliente = Integer.parseInt(item.getString());
                        }
                        if (item.getFieldName().equals("vd")) {
                            vd = Integer.parseInt(item.getString());
                        }
                        if (item.getFieldName().equals("ar")) {
                            ar = Integer.parseInt(item.getString());
                        }
                        if (item.getFieldName().equals("rm")) {
                            rm = Integer.parseInt(item.getString());
                        }
                        if (item.getFieldName().equals("tipoEntrega")) {
                            tipoEntrega = Integer.parseInt(item.getString());
                        }
                    }

                    if (!item.isFormField()) {
                        if (item.getName().length() > 0) {
                            listaArq.add(item);
                        }
                    }
                }

                if (listaArq.isEmpty()) {
                    response.sendRedirect(
                            "Cliente/Servicos/imp_postagem.jsp?msg=Escolha um arquivo para importacao !");
                } else if (listaArq.size() > 200) {
                    response.sendRedirect(
                            "Cliente/Servicos/imp_postagem.jsp?msg=Importacao maxima de 200 arquivos de cada vez!");
                } else {
                    ContrPreVendaImporta.excluirNaoConfirmados(idCliente, nomeBD);
                    String condicao = ContrPreVendaImporta.importaPedidoNFe(listaArq, idCliente, departamento,
                            servico, vd, ar, rm, tipoEntrega, nomeBD);
                    if (condicao.startsWith("ERRO")) {
                        response.sendRedirect("Cliente/Servicos/imp_postagem.jsp?msg=" + condicao);
                    } else {
                        response.sendRedirect("Cliente/Servicos/imp_confirma.jsp?msg=" + condicao);
                    }
                }

            } catch (FileUploadException ex) {
                response.sendRedirect("Cliente/Servicos/imp_postagem.jsp?msg=Falha na importacao!\n" + ex);
            } catch (Exception ex) {
                response.sendRedirect("Cliente/Servicos/imp_postagem.jsp?msg=Falha na importacao!\n" + ex);
            }

        } else {
            response.sendRedirect("Cliente/Servicos/imp_postagem.jsp?msg=is not a multipart form");
        }
    } else {
        response.sendRedirect("Cliente/Servicos/imp_postagem.jsp?msg=Sua sessao expirou!");
    }

}

From source file:com.app.framework.web.MultipartFilter.java

/**
 * Process multipart request item as regular form field. The name and value
 * of each regular form field will be added to the given parameterMap.
 *
 * @param formField The form field to be processed.
 * @param parameterMap The parameterMap to be used for the
 * HttpServletRequest./*from   ww w.j  av a 2s .c  o m*/
 */
private void processFormField(FileItem formField, Map<String, String[]> parameterMap) {
    String name = formField.getFieldName();
    String value = formField.getString();
    String[] values = parameterMap.get(name);

    if (values == null) {
        // Not in parameter map yet, so add as new value.
        parameterMap.put(name, new String[] { value });
    } else {
        // Multiple field values, so add new value to existing array.
        int length = values.length;
        String[] newValues = new String[length + 1];
        System.arraycopy(values, 0, newValues, 0, length);
        newValues[length] = value;
        parameterMap.put(name, newValues);
    }
}

From source file:com.tern.web.MultiPartEnabledRequest.java

private void readHttpParams(HttpServletRequest req) throws FileUploadException {
    List all = uploadFiles(req);//  w  ww.  j a v a 2 s.  c  o  m

    // read form fields
    for (Iterator it = all.iterator(); it.hasNext();) {
        FileItem item = (FileItem) it.next();

        if (item.isFormField()) {
            List valList = valueList(httpParams, item.getFieldName());
            if (req.getCharacterEncoding() != null) {
                try {
                    valList.add(item.getString(req.getCharacterEncoding()));
                } catch (UnsupportedEncodingException e) {
                    Trace.write(Trace.Error, e, "");
                    valList.add(item.getString(/*encoding?*/));
                }
            } else
                valList.add(item.getString(/*encoding?*/));
        } else {
            List valList = valueList(fileItems, item.getFieldName());
            valList.add(item);
        }
    }

    // convert lists of values to arrays
    for (Iterator it = httpParams.keySet().iterator(); it.hasNext();) {
        String name = (String) it.next();
        List valList = (List) httpParams.get(name);
        httpParams.put(name, toStringArray(valList));
    }

    for (Iterator it = fileItems.keySet().iterator(); it.hasNext();) {
        String name = (String) it.next();
        List valList = (List) fileItems.get(name);
        fileItems.put(name, toFileItemArray(valList));
    }
}