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

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

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItemStream 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:pl.exsio.plupload.PluploadChunkFactory.java

private static void setChunkField(PluploadChunk chunk, FileItemStream item)
        throws NumberFormatException, IOException {
    String value = Streams.asString(item.openStream());
    switch (item.getFieldName()) {
    case "fileId":
        chunk.setFileId(value);/*w w  w .  j av a  2  s  .  c om*/
        break;
    case "name":
        chunk.setName(value);
        break;
    case "chunk":
        chunk.setChunk(Integer.parseInt(value));
        break;
    case "chunks":
        chunk.setChunks(Integer.parseInt(value));
    }
}

From source file:Project.FileUploadServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//w w  w  .j a 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
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //processRequest(request, response);
    response.setContentType("text/html");
    String path = "";
    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
    if (isMultiPart) {
        ServletFileUpload upload = new ServletFileUpload();
        try {
            String category = "";
            String keywords = "";
            double cost = 0.0;
            String imagess = "";
            String user = "";
            FileItemIterator itr = upload.getItemIterator(request);
            Map<String, String> map = new HashMap<String, String>();
            while (itr.hasNext()) {
                FileItemStream item = itr.next();
                if (item.isFormField()) {
                    //do variable declaration of the specific field
                    String fieldName = item.getFieldName();
                    InputStream is = item.openStream();
                    byte[] b = new byte[is.available()];
                    is.read(b);
                    String value = new String(b);
                    response.getWriter().println(fieldName + ":" + value + "<br/>");
                    map.put(fieldName, value);
                } else {
                    //do file upload and store the path as variable
                    path = getServletContext().getRealPath("/");
                    //will write a method and we will call here
                    if (processFile(path, item)) {
                        response.getWriter().println("File uploaded successfully");
                        response.getWriter().println(path);
                    } else {
                        response.getWriter().println("File uploading failed");
                    }
                }

                for (Map.Entry<String, String> entry : map.entrySet()) {
                    if (entry.getKey().equals("category")) {
                        category = entry.getValue();
                    } else if (entry.getKey().equals("keywords")) {
                        keywords = entry.getValue();
                    } else if (entry.getKey().equals("cost")) {
                        cost = Double.parseDouble(entry.getValue());
                    } else if (entry.getKey().equals("fileName")) {
                        imagess = entry.getValue();
                    } else if (entry.getKey().equals("user")) {
                        user = entry.getValue();
                    }
                }

            }
            response.getWriter().println("images\\" + imagess);
            imagess = "images\\" + imagess;
            response.getWriter().println(category + "---" + keywords + "----" + cost + "---" + imagess);
            DB_Users d = new DB_Users();
            d.insertProduct(category, keywords, imagess, cost, user);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    } else {
        //do nothing
    }
}

From source file:ru.arch_timeline.spring.multipart.StreamingMultipartResolver.java

public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();
    upload.setFileSizeMax(maxUploadSize);

    String encoding = determineEncoding(request);

    //Map<String, MultipartFile> multipartFiles = new HashMap<String, MultipartFile>();
    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();
    Map<String, String> multipartContentTypes = new HashMap<String, String>();

    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>();

    // Parse the request
    try {/*w  w w.j  a v a2  s.com*/
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();

            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {

                String value = Streams.asString(stream, encoding);

                String[] curParam = (String[]) multipartParameters.get(name);
                if (curParam == null) {
                    // simple form field
                    multipartParameters.put(name, new String[] { value });
                } else {
                    // array of simple form fields
                    String[] newParam = StringUtils.addStringToArray(curParam, value);
                    multipartParameters.put(name, newParam);
                }

            } else {

                // Process the input stream
                MultipartFile file = new StreamingMultipartFile(item);
                multipartFiles.add(name, file);
                multipartContentTypes.put(name, file.getContentType());
            }
        }
    } catch (IOException e) {
        throw new MultipartException("something went wrong here", e);
    } catch (FileUploadException e) {
        throw new MultipartException("something went wrong here", e);
    }

    return new DefaultMultipartHttpServletRequest(request, multipartFiles, multipartParameters,
            multipartContentTypes);
}

From source file:rurales.FileUploadRural.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from  w  ww. jav  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 doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ConectionDB con = new ConectionDB();
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String Unidad = "";

    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
    if (isMultiPart) {
        ServletFileUpload upload = new ServletFileUpload();
        try {
            HttpSession sesion = request.getSession(true);
            FileItemIterator itr = upload.getItemIterator(request);
            while (itr.hasNext()) {
                FileItemStream item = itr.next();
                if (item.isFormField()) {
                    String fielName = item.getFieldName();
                    InputStream is = item.openStream();
                    byte[] b = new byte[is.available()];
                    is.read(b);
                    String value = new String(b);
                    response.getWriter().println(fielName + ":" + value + "<br/>");
                } else {
                    String path = getServletContext().getRealPath("/");
                    if (FileUpload.processFile(path, item)) {
                        //response.getWriter().println("file uploaded successfully");
                        if (lee.obtieneArchivo(path, item.getName())) {
                            out.println("<script>alert('Se carg el Folio Correctamente')</script>");
                            out.println("<script>window.location='requerimiento.jsp'</script>");
                        }
                        //response.sendRedirect("cargaFotosCensos.jsp");
                    } else {
                        //response.getWriter().println("file uploading falied");
                        //response.sendRedirect("cargaFotosCensos.jsp");
                    }
                }
            }
        } catch (FileUploadException fue) {
            fue.printStackTrace();
        }
        out.println("<script>alert('No se pudo cargar el Folio, verifique las celdas')</script>");
        out.println("<script>window.location='requerimiento.jsp'</script>");
        //response.sendRedirect("carga.jsp");
    }

    /*
     * Para insertar el excel en tablas
     */
}

From source file:se.vgregion.portal.innovationsslussen.idea.controller.IdeaViewController.java

/**
 * Upload file action./*from  w w w .j av  a  2s.  c om*/
 *
 * @param request  the request
 * @param response the response
 * @param model    the model
 * @throws FileUploadException the file upload exception
 */
@ActionMapping(params = "action=uploadFile")
public void uploadFile(ActionRequest request, ActionResponse response, Model model)
        throws FileUploadException, SystemException, PortalException {

    ThemeDisplay themeDisplay = getThemeDisplay(request);
    long scopeGroupId = themeDisplay.getScopeGroupId();
    long userId = themeDisplay.getUserId();

    String urlTitle = request.getParameter("urlTitle");

    String fileType = request.getParameter("fileType");
    boolean publicIdea;
    if (fileType.equals("public")) {
        publicIdea = true;
    } else if (fileType.equals("private")) {
        publicIdea = false;
    } else {
        throw new IllegalArgumentException("Unknown filetype: " + fileType);
    }

    //TODO ondig slagning? Cacha?
    Idea idea = ideaService.findIdeaByUrlTitle(urlTitle);
    //TODO Kan det inte finnas flera med samma titel i olika communities?

    IdeaContentType ideaContentType = publicIdea ? IdeaContentType.IDEA_CONTENT_TYPE_PUBLIC
            : IdeaContentType.IDEA_CONTENT_TYPE_PRIVATE;

    if (!isAllowedToDoAction(request, idea, Action.UPLOAD_FILE, ideaContentType)) {
        sendRedirectToContextRoot(response);
        return;
    }

    boolean mayUploadFile = idea.getUserId() == userId;

    IdeaPermissionChecker ideaPermissionChecker = ideaPermissionCheckerService
            .getIdeaPermissionChecker(scopeGroupId, userId, idea);

    if (!mayUploadFile) {
        if (publicIdea) {
            mayUploadFile = ideaPermissionChecker.isHasPermissionAddDocumentPublic();
        } else {
            mayUploadFile = ideaPermissionChecker.isHasPermissionAddDocumentPrivate();
        }
    }

    if (mayUploadFile) {
        response.setRenderParameter("urlTitle", urlTitle);

        PortletFileUpload p = new PortletFileUpload();

        try {
            FileItemIterator itemIterator = p.getItemIterator(request);

            while (itemIterator.hasNext()) {
                FileItemStream fileItemStream = itemIterator.next();

                if (fileItemStream.getFieldName().equals("file")) {

                    InputStream is = fileItemStream.openStream();
                    BufferedInputStream bis = new BufferedInputStream(is);

                    String fileName = fileItemStream.getName();
                    String contentType = fileItemStream.getContentType();

                    ideaService.uploadFile(idea, publicIdea, fileName, contentType, bis);
                }
            }
        } catch (FileUploadException e) {
            doExceptionStuff(e, response, model);
            return;
        } catch (IOException e) {
            doExceptionStuff(e, response, model);
            return;
        } catch (se.vgregion.service.innovationsslussen.exception.FileUploadException e) {
            doExceptionStuff(e, response, model);
            return;
        } catch (RuntimeException e) {
            Throwable lastCause = Util.getLastCause(e);
            if (lastCause instanceof SQLException) {
                SQLException nextException = ((SQLException) lastCause).getNextException();
                if (nextException != null) {
                    LOGGER.error(nextException.getMessage(), nextException);
                }
            }
        } finally {
            response.setRenderParameter("ideaType", fileType);
        }
    } else {
        throw new FileUploadException("The user is not authorized to upload to this idea instance.");
    }

    response.setRenderParameter("urlTitle", urlTitle);
    response.setRenderParameter("type", fileType);
    response.setRenderParameter("showView", "showIdea");
}

From source file:tech.oleks.pmtalk.PmTalkServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Order o = new Order();
    ServletFileUpload upload = new ServletFileUpload();
    try {//w  w w . ja  v a 2 s.  c  om
        FileItemIterator it = upload.getItemIterator(req);
        while (it.hasNext()) {
            FileItemStream item = it.next();
            InputStream fieldValue = item.openStream();
            String fieldName = item.getFieldName();
            if ("candidate".equals(fieldName)) {
                String candidate = Streams.asString(fieldValue);
                o.setCandidate(candidate);
            } else if ("staffing".equals(fieldName)) {
                String staffingLink = Streams.asString(fieldValue);
                o.setStaffingLink(staffingLink);
            } else if ("resume".equals(fieldName)) {
                FileUpload resume = new FileUpload();
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                IOUtils.copy(fieldValue, os);
                resume.setStream(new ByteArrayInputStream(os.toByteArray()));
                resume.setContentType(item.getContentType());
                resume.setFileName(item.getName());
                o.setResume(resume);
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    }

    pmTalkService.minimal(o);
    req.setAttribute("order", o);
    if (o.getErrors() != null) {
        forward("/form.jsp", req, resp);
    } else {
        forward("/created.jsp", req, resp);
    }
}

From source file:temporal.web.DemoServlet.java

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

    InputStream in = null;/*from  w  ww  . java2 s. co  m*/
    OutputStream out = null;

    try {
        response.setContentType(mDemo.responseType());
        out = response.getOutputStream();

        @SuppressWarnings("unchecked") // bad inherited API from commons
        Properties properties = mapToProperties((Map<String, String[]>) request.getParameterMap());

        String reqContentType = request.getContentType();

        if (reqContentType == null || reqContentType.startsWith("text/plain")) {
            properties.setProperty("inputType", "text/plain");
            String reqCharset = request.getCharacterEncoding();
            if (reqCharset != null)
                properties.setProperty("inputCharset", reqCharset);
            in = request.getInputStream();

        } else if (reqContentType.startsWith("application/x-www-form-urlencoded")) {
            String codedText = request.getParameter("inputText");
            byte[] bytes = codedText.getBytes("ISO-8859-1");
            in = new ByteArrayInputStream(bytes);

        } else if (ServletFileUpload.isMultipartContent(new ServletRequestContext(request))) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload uploader = new ServletFileUpload(factory);
            FileItemIterator it = uploader.getItemIterator(request);
            /*  @SuppressWarnings("unchecked") // bad commons API
            /*  List<FileItem> items = (List<FileItem>) uploader.parseRequest(request);
              Iterator<FileItem> it = items.iterator();*/
            while (it.hasNext()) {
                log("found item");
                FileItemStream item = it.next();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    String key = item.getFieldName();
                    //   String val = item.getString();
                    String val = org.apache.commons.fileupload.util.Streams.asString(stream);
                    properties.setProperty(key, val);
                } else {
                    byte[] bytes = org.apache.commons.fileupload.util.Streams.asString(stream).getBytes();
                    in = new ByteArrayInputStream(bytes);
                }
            }

        } else {
            System.out.println("unexpected content type");
            String msg = "Unexpected request content" + reqContentType;
            throw new ServletException(msg);
        }
        mDemo.process(in, out, properties);
    } catch (FileUploadException e) {
        throw new ServletException(e);
    } finally {
        Streams.closeQuietly(in);
        Streams.closeQuietly(out);
    }
}

From source file:uk.ac.ebi.sail.server.service.UploadSvc.java

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);

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

    String res = null;/* www.  j a v a2  s .  com*/
    int studyID = -1;
    int collectionID = -1;

    String fileContent = null;

    String upType = null;

    try {
        // Parse the request
        FileItemIterator iter = upload.getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                if ("CollectionID".equals(name)) {
                    try {
                        collectionID = Integer.parseInt(Streams.asString(stream));
                    } catch (Exception e) {
                    }
                }
                if ("StudyID".equals(name)) {
                    try {
                        studyID = Integer.parseInt(Streams.asString(stream));
                    } catch (Exception e) {
                    }
                } else if ("UploadType".equals(name)) {
                    upType = Streams.asString(stream);
                }

                //     System.out.println("Form field " + name + " with value " + Streams.asString(stream) + " detected.");
            } else {
                //     System.out.println("File field " + name + " with file name " + item.getName() + " detected.");
                InputStream uploadedStream = item.openStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();

                StreamPump.doPump(uploadedStream, baos);

                byte[] barr = baos.toByteArray();

                if ((barr[0] == -1 && barr[1] == -2) || (barr[0] == -2 && barr[1] == -1))
                    fileContent = new String(barr, "UTF-16");
                else
                    fileContent = new String(barr);
            }
        }
    } catch (Exception ex) {
        res = ex.getMessage();
        ex.printStackTrace();
    }

    if (fileContent != null) {
        if ("AvailabilityData".equals(upType)) {
            if (collectionID != -1) {
                try {
                    DataManager.getInstance().importData(fileContent, collectionID);
                } catch (Exception ex) {
                    res = ex.getMessage();
                    ex.printStackTrace();
                }
            } else
                res = "Invalid or absent collection ID";
        } else if ("RelationMap".equals(upType)) {
            try {
                DataManager.getInstance().importRelations(new String(fileContent));
            } catch (Exception ex) {
                res = ex.getMessage();
                ex.printStackTrace();
            }
        } else if ("Study2SampleRelation".equals(upType)) {
            try {
                DataManager.getInstance().importSample2StudyRelations(new String(fileContent), studyID,
                        collectionID);
            } catch (Exception ex) {
                res = ex.getMessage();
                ex.printStackTrace();
            }
        } else {
            try {
                DataManager.getInstance().importParameters(fileContent);
            } catch (ParseException pex) {
                res = "Line " + pex.getLineNumber() + ": " + pex.getMessage();
            } catch (Exception ex) {
                res = ex.getMessage();
                ex.printStackTrace();
            }

        }

    } else {
        res = "File content not found";
    }

    JSONObject response = null;
    try {
        response = new JSONObject();
        response.put("success", res == null);
        response.put("error", res == null ? "uploaded successfully" : res);
        response.put("code", "232");
    } catch (Exception e) {

    }

    Writer w = new OutputStreamWriter(resp.getOutputStream());
    w.write(response.toString());
    System.out.println(response.toString());
    w.close();
    resp.setStatus(HttpServletResponse.SC_OK);
}

From source file:us.mn.state.health.lims.analyzerimport.action.AnalyzerImportServlet.java

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

    String password = null;//from   ww w.j  av a  2  s .c om
    String user = null;
    AnalyzerReader reader = null;
    boolean fileRead = false;

    InputStream stream = null;

    try {
        ServletFileUpload upload = new ServletFileUpload();

        FileItemIterator iterator = upload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            stream = item.openStream();

            String name = null;

            if (item.isFormField()) {

                if (PASSWORD.equals(item.getFieldName())) {
                    password = streamToString(stream);
                } else if (USER.equals(item.getFieldName())) {
                    user = streamToString(stream);
                }

            } else {

                name = item.getName();

                reader = AnalyzerReaderFactory.getReaderFor(name);

                if (reader != null) {
                    fileRead = reader.readStream(new InputStreamReader(stream));
                }
            }

            stream.close();
        }
    } catch (Exception ex) {
        throw new ServletException(ex);
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                //   LOG.warning(e.toString());
            }
        }
    }

    if (GenericValidator.isBlankOrNull(user) || GenericValidator.isBlankOrNull(password)) {
        response.getWriter().print("missing user");
        response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
        return;
    }

    if (!userValid(user, password)) {
        response.getWriter().print("invalid user/password");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    if (fileRead) {
        boolean successful = reader.insertAnalyzerData(systemUserId);

        if (successful) {
            response.getWriter().print("success");
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        } else {
            response.getWriter().print(reader.getError());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }

    } else {
        response.getWriter().print(reader.getError());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

}

From source file:zutil.jee.upload.AjaxFileUpload.java

@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    FileUploadListener listener = new FileUploadListener();
    try {//from   w  w  w .ja v  a  2s  .  c  om
        // Initiate list and HashMap that will contain the data
        HashMap<String, String> fields = new HashMap<String, String>();
        ArrayList<FileItem> files = new ArrayList<FileItem>();

        // Add the listener to the session
        HttpSession session = request.getSession();
        LinkedList<FileUploadListener> list = (LinkedList<FileUploadListener>) session
                .getAttribute(SESSION_FILEUPLOAD_LISTENER);
        if (list == null) {
            list = new LinkedList<FileUploadListener>();
            session.setAttribute(SESSION_FILEUPLOAD_LISTENER, list);
        }
        list.add(listener);

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
        if (TEMPFILE_PATH != null)
            factory.setRepository(TEMPFILE_PATH);
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setProgressListener(listener);
        // Set overall request size constraint
        //upload.setSizeMax(yourMaxRequestSize);

        // Parse the request
        FileItemIterator it = upload.getItemIterator(request);
        while (it.hasNext()) {
            FileItemStream item = it.next();
            // Is the file type allowed?
            if (!item.isFormField()
                    && !ALLOWED_EXTENSIONS.contains(FileUtil.getFileExtension(item.getName()).toLowerCase())) {
                String msg = "Filetype '" + FileUtil.getFileExtension(item.getName()) + "' is not allowed!";
                logger.warning(msg);
                listener.setStatus(Status.Error);
                listener.setFileName(item.getName());
                listener.setMessage(msg);
                return;
            }
            listener.setFileName(item.getName());
            FileItem fileItem = factory.createItem(item.getFieldName(), item.getContentType(),
                    item.isFormField(), item.getName());
            // Read the file data
            Streams.copy(item.openStream(), fileItem.getOutputStream(), true);
            if (fileItem instanceof FileItemHeadersSupport) {
                final FileItemHeaders fih = item.getHeaders();
                ((FileItemHeadersSupport) fileItem).setHeaders(fih);
            }

            //Handle the item
            if (fileItem.isFormField()) {
                fields.put(fileItem.getFieldName(), fileItem.getString());
            } else {
                files.add(fileItem);
                logger.info("Recieved file: " + fileItem.getName() + " ("
                        + StringUtil.formatByteSizeToString(fileItem.getSize()) + ")");
            }
        }
        // Process the upload
        listener.setStatus(Status.Processing);
        doUpload(request, response, fields, files);
        // Done
        listener.setStatus(Status.Done);
    } catch (Exception e) {
        logger.log(Level.SEVERE, null, e);
        listener.setStatus(Status.Error);
        listener.setFileName("");
        listener.setMessage(e.getMessage());
    }
}