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:guru.nidi.ramltester.util.FormDecoder.java

private Values decodeMultipart(RamlRequest request) {
    try {//  ww w  . j a va2  s.  co m
        final Values values = new Values();
        final RamlRequestFileUploadContext context = new RamlRequestFileUploadContext(request);
        final FileItemIterator iter = new ServletFileUpload().getItemIterator(context);
        while (iter.hasNext()) {
            final FileItemStream itemStream = iter.next();
            values.addValue(itemStream.getFieldName(), valueOf(itemStream));
        }
        return values;
    } catch (IOException | FileUploadException e) {
        throw new IllegalArgumentException("Could not parse multipart request", e);
    }
}

From source file:com.example.getstarted.basicactions.CreateBookServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    assert ServletFileUpload.isMultipartContent(req);
    CloudStorageHelper storageHelper = (CloudStorageHelper) getServletContext().getAttribute("storageHelper");

    String newImageUrl = null;/* w  ww  .j  a va  2  s  .  c o m*/
    Map<String, String> params = new HashMap<String, String>();
    try {
        FileItemIterator iter = new ServletFileUpload().getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), Streams.asString(item.openStream()));
            } else if (!Strings.isNullOrEmpty(item.getName())) {
                newImageUrl = storageHelper.uploadFile(item,
                        getServletContext().getInitParameter("bookshelf.bucket"));
            }
        }
    } catch (FileUploadException e) {
        throw new IOException(e);
    }

    String createdByString = "";
    String createdByIdString = "";
    HttpSession session = req.getSession();
    if (session.getAttribute("userEmail") != null) { // Does the user have a logged in session?
        createdByString = (String) session.getAttribute("userEmail");
        createdByIdString = (String) session.getAttribute("userId");
    }

    Book book = new Book.Builder().author(params.get("author")).description(params.get("description"))
            .publishedDate(params.get("publishedDate")).title(params.get("title"))
            .imageUrl(null == newImageUrl ? params.get("imageUrl") : newImageUrl).createdBy(createdByString)
            .createdById(createdByIdString).build();

    BookDao dao = (BookDao) this.getServletContext().getAttribute("dao");
    try {
        Long id = dao.createBook(book);
        logger.log(Level.INFO, "Created book {0}", book);
        resp.sendRedirect("/read?id=" + id.toString()); // read what we just wrote
    } catch (Exception e) {
        throw new ServletException("Error creating book", e);
    }
}

From source file:com.threewks.thundr.bind.http.MultipartHttpBinder.java

void extractParameters(HttpServletRequest req, Map<String, List<String>> formFields,
        Map<String, MultipartFile> fileFields) {
    try {//from w w w  . j ava  2  s .co m
        FileItemIterator itemIterator = upload.getItemIterator(req);
        while (itemIterator.hasNext()) {
            FileItemStream item = itemIterator.next();
            InputStream stream = item.openStream();

            String fieldName = item.getFieldName();
            if (item.isFormField()) {
                List<String> existing = formFields.get(fieldName);
                if (existing == null) {
                    existing = new LinkedList<String>();
                    formFields.put(fieldName, existing);
                }
                existing.add(Streams.readString(stream));
            } else {
                MultipartFile file = new MultipartFile(item.getName(), Streams.readBytes(stream),
                        item.getContentType());
                fileFields.put(fieldName, file);
            }
            stream.close();
        }
    } catch (Exception e) {
        throw new BindException(e, "Failed to bind multipart form data: %s", e.getMessage());
    }
}

From source file:com.runwaysdk.web.WebFileUploadServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    ClientRequestIF clientRequest = (ClientRequestIF) req.getAttribute(ClientConstants.CLIENTREQUEST);

    // capture the session id
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);

    if (!isMultipart) {
        // TODO Change exception type
        String msg = "The HTTP Request must contain multipart content.";
        throw new RuntimeException(msg);
    }/*from   w  w  w  .  ja  v a 2s. co m*/

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload();

    upload.setFileItemFactory(factory);

    try {
        // Parse the request
        FileItemIterator iter = upload.getItemIterator(req);

        String fileName = null;
        String extension = null;
        InputStream stream = null;
        String uploadPath = null;
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            InputStream input = item.openStream();
            if (item.isFormField() && item.getFieldName().equals(WEB_FILE_UPLOAD_PATH_FIELD_NAME)) {
                uploadPath = Streams.asString(input);
            } else if (!item.isFormField()) {
                String fullName = item.getName();
                int extensionInd = fullName.lastIndexOf(".");
                fileName = fullName.substring(0, extensionInd);
                extension = fullName.substring(extensionInd + 1);
                stream = input;
            }
        }

        if (stream != null) {
            clientRequest.newFile(uploadPath, fileName, extension, stream);
        }
    } catch (FileUploadException e) {
        throw new FileWriteExceptionDTO(e.getLocalizedMessage());
    }
}

From source file:DBMS.PicUpdateServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from  w  w  w .j  av  a 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 {
    response.setContentType("text/html;charset=UTF-8");
    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
    if (isMultiPart) {
        ServletFileUpload upload = new ServletFileUpload();
        try {
            FileItemIterator itr = upload.getItemIterator(request);
            while (itr.hasNext()) {
                FileItemStream item = itr.next();
                if (item.isFormField()) {
                    String fieldName = item.getFieldName();
                    InputStream is = item.openStream();
                    byte[] b = new byte[is.available()];
                    is.read(b);
                    String value = new String(b);
                    System.out.println("Getting");
                } else {
                    String path = getServletContext().getRealPath("/");
                    loginid lid = null;
                    HttpSession session = request.getSession();
                    lid = (loginid) session.getAttribute("lid");
                    int id = lid.getId();
                    if (UpdateFileUpload.processFile(path, item, id)) {
                        response.sendRedirect("ProfilePicUpdateSuccess.jsp");
                    } else
                        response.sendRedirect("ProfilePicUpdateFailed.jsp");
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.serli.chell.framework.upload.FileUploadInfo.java

private FileUploadInfo(FileItemStream fis, String fileName, String charsetEncoding) {
    this.fis = fis;
    this.fileName = fileName;
    this.fieldName = fis.getFieldName();
    this.charsetEncoding = charsetEncoding;
    this.item = null;
    if (fileName == null) {
        this.extension = null;
        this.contentType = null;
        this.size = 0;
    } else {/*from   w  w  w .  ja  v  a 2  s. c  om*/
        this.extension = FileUtils.extension(fileName);
        this.contentType = getContentType(fis.getContentType(), extension);
        this.size = Constant.UNSPECIFIED;
    }
}

From source file:fedora.server.management.UploadServlet.java

/**
 * The servlet entry point. http://host:port/fedora/management/upload
 *///w ww  .j  a  v a 2 s. co  m
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Context context = ReadOnlyContext.getContext(Constants.HTTP_REQUEST.REST.uri, request);
    try {
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload();

        // Parse the request, looking for "file"
        InputStream in = null;
        FileItemIterator iter = upload.getItemIterator(request);
        while (in == null && iter.hasNext()) {
            FileItemStream item = iter.next();
            LOG.info("Got next item: isFormField=" + item.isFormField() + " fieldName=" + item.getFieldName());
            if (!item.isFormField() && item.getFieldName().equals("file")) {
                in = item.openStream();
            }
        }
        if (in == null) {
            sendResponse(HttpServletResponse.SC_BAD_REQUEST, "No data sent.", response);
        } else {
            sendResponse(HttpServletResponse.SC_CREATED, s_management.putTempStream(context, in), response);
        }
    } catch (AuthzException ae) {
        throw RootException.getServletException(ae, request, "Upload", new String[0]);
    } catch (Exception e) {
        e.printStackTrace();
        sendResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                e.getClass().getName() + ": " + e.getMessage(), response);
    }
}

From source file:controllers.UploadController.java

/**
 * /*from  ww  w  . j  a v a  2s.c o  m*/
 * This upload method expects a file and simply displays the file in the
 * multipart upload again to the user (in the correct mime encoding).
 * 
 * @param context
 * @return
 * @throws Exception
 */
public Result uploadFinish(Context context) throws Exception {

    // we are using a renderable inner class to stream the input again to
    // the user
    Renderable renderable = new Renderable() {

        @Override
        public void render(Context context, Result result) {

            try {
                // make sure the context really is a multipart context...
                if (context.isMultipart()) {

                    // This is the iterator we can use to iterate over the
                    // contents
                    // of the request.
                    FileItemIterator fileItemIterator = context.getFileItemIterator();

                    while (fileItemIterator.hasNext()) {

                        FileItemStream item = fileItemIterator.next();

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

                        String contentType = item.getContentType();

                        if (contentType != null) {
                            result.contentType(contentType);
                        } else {
                            contentType = mimeTypes.getMimeType(name);
                        }

                        ResponseStreams responseStreams = context.finalizeHeaders(result);

                        if (item.isFormField()) {
                            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.");
                            // Process the input stream

                            ByteStreams.copy(stream, responseStreams.getOutputStream());

                        }
                    }

                }

            } catch (IOException | FileUploadException exception) {

                throw new InternalServerErrorException(exception);

            }

        }
    };

    return new Result(200).render(renderable);

}

From source file:in.co.sneh.controller.CargaExcelRural.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// www . 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 {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        CargaExcelReqRural lee = new CargaExcelReqRural();
        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 (CargaExcelRuralModel.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='facturacionRural/cargaRequerimento.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");
        }
    } finally {
        out.close();
    }
}

From source file:Functions.UploadFileServlet.java

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

    String houseId = "";
    String owner = (String) request.getSession().getAttribute("username");
    String url = "/errorPage.jsp";
    String message = "fgd";
    //System.out.println("houseId= "+houseId);
    //System.out.println("owner= "+owner);
    response.setContentType("text/html");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();
        try {//from w  ww.  j av a2s. c o m
            FileItemIterator itr = upload.getItemIterator(request);
            while (itr.hasNext()) {
                FileItemStream item = itr.next();
                if (item.isFormField()) {
                    //do something
                    String fieldName = item.getFieldName();
                    InputStream is = item.openStream();
                    byte b[] = new byte[is.available()];
                    is.read(b);
                    String value = new String(b);
                    if ("houseIddd".equals(fieldName)) {
                        houseId = value;
                    }
                    response.getWriter().println(fieldName + ":" + value + "<br/>");
                } else {
                    System.out.println("MPHKE STO ELSE GIA NA BALEI SPITIA");
                    //upload file
                    String path = getServletContext().getRealPath("/");
                    //String path = getServletContext().getContextPath()+"/";

                    if (FileUpload.processFile(path, item, houseId, owner)) {
                        System.out.println("MPHKE STO processfile!");
                        //response.getWriter().println("file uploaded successfully");
                        message = "file uploaded successfully";

                        url = "/Estateprofile.jsp?houseId=" + houseId + "&houseOwner=" + owner + "&message="
                                + message;

                    } else {
                        message = "file uploading failed";
                        url = "/Estateprofile.jsp?houseId=" + houseId + "&houseOwner=" + owner + "&message="
                                + message;

                        //response.getWriter().println("file uploading failed");
                    }
                }
            }
        } catch (FileUploadException ex) {
            ex.printStackTrace();
            //Logger.getLogger(UploadFileServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
        dispatcher.forward(request, response);
    }
}