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

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

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItemStream openStream.

Prototype

InputStream openStream() throws IOException;

Source Link

Document

Creates an InputStream , which allows to read the items contents.

Usage

From source file:password.pwm.http.PwmRequest.java

public Map<String, FileUploadItem> readFileUploads(final int maxFileSize, final int maxItems)
        throws IOException, ServletException, PwmUnrecoverableException {
    final Map<String, FileUploadItem> returnObj = new LinkedHashMap<>();
    try {//from  w ww.j a  va2 s.c  o m
        if (ServletFileUpload.isMultipartContent(this.getHttpServletRequest())) {
            final ServletFileUpload upload = new ServletFileUpload();
            final FileItemIterator iter = upload.getItemIterator(this.getHttpServletRequest());
            while (iter.hasNext() && returnObj.size() < maxItems) {
                final FileItemStream item = iter.next();
                final InputStream inputStream = item.openStream();
                final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                final long length = IOUtils.copyLarge(inputStream, baos, 0, maxFileSize + 1);
                if (length > maxFileSize) {
                    final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNKNOWN,
                            "upload file size limit exceeded");
                    LOGGER.error(this, errorInformation);
                    respondWithError(errorInformation);
                    return Collections.emptyMap();
                }
                final byte[] outputFile = baos.toByteArray();
                final FileUploadItem fileUploadItem = new FileUploadItem(item.getName(), item.getContentType(),
                        outputFile);
                returnObj.put(item.getFieldName(), fileUploadItem);
            }
        }
    } catch (Exception e) {
        LOGGER.error("error reading file upload: " + e.getMessage());
    }
    return Collections.unmodifiableMap(returnObj);
}

From source file:password.pwm.http.ServletHelper.java

public static String readFileUpload(final HttpServletRequest req, final String filePartName, int maxFileChars)
        throws IOException, ServletException, PwmUnrecoverableException {
    try {/*from   w w w. j  a  va2 s.c o  m*/
        if (ServletFileUpload.isMultipartContent(req)) {

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

            String uploadFile = null;

            // Parse the request
            for (final FileItemIterator iter = upload.getItemIterator(req); iter.hasNext();) {
                final FileItemStream item = iter.next();

                if (filePartName.equals(item.getFieldName())) {
                    uploadFile = streamToString(item.openStream(), maxFileChars);
                }
            }

            return uploadFile;
        }
    } catch (Exception e) {
        LOGGER.error("error reading file upload: " + e.getMessage());
    }
    return null;
}

From source file:password.pwm.http.ServletHelper.java

public static InputStream readFileUpload(final HttpServletRequest req, final String filePartName)
        throws IOException, ServletException, PwmUnrecoverableException {
    try {//from  w  w w . j  a  v  a2 s. c  o m
        if (ServletFileUpload.isMultipartContent(req)) {

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

            // Parse the request
            for (final FileItemIterator iter = upload.getItemIterator(req); iter.hasNext();) {
                final FileItemStream item = iter.next();

                if (filePartName.equals(item.getFieldName())) {
                    return item.openStream();
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error("error reading file upload: " + e.getMessage());
    }
    return null;
}

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);/*  ww  w.  ja v  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:pl.exsio.plupload.PluploadChunkFactory.java

private static void saveChunkData(PluploadChunk chunk, FileItemStream item) throws IOException {
    if (getReceiver().isFileExpected(chunk.getFileId())) {
        chunk.setInputStream(item.openStream());
    }//from w w w  .j  av  a  2  s  . co m
}

From source file:play.data.parsing.ApacheMultipartParser.java

public Map<String, String[]> parse(InputStream body) {
    Map<String, String[]> result = new HashMap<String, String[]>();
    try {//ww  w  .j av  a 2s .c  om
        FileItemIteratorImpl iter = new FileItemIteratorImpl(body,
                Request.current().headers.get("content-type").value(), Request.current().encoding);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            FileItem fileItem = new AutoFileItem(item);
            try {
                Streams.copy(item.openStream(), fileItem.getOutputStream(), true);
            } catch (FileUploadIOException e) {
                throw (FileUploadException) e.getCause();
            } catch (IOException e) {
                throw new IOFileUploadException(
                        "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage(), e);
            }
            if (fileItem.isFormField()) {
                // must resolve encoding
                String _encoding = Request.current().encoding; // this is our default
                String _contentType = fileItem.getContentType();
                if (_contentType != null) {
                    HTTP.ContentTypeWithEncoding contentTypeEncoding = HTTP.parseContentType(_contentType);
                    if (contentTypeEncoding.encoding != null) {
                        _encoding = contentTypeEncoding.encoding;
                    }
                }

                putMapEntry(result, fileItem.getFieldName(), fileItem.getString(_encoding));
            } else {
                @SuppressWarnings("unchecked")
                List<Upload> uploads = (List<Upload>) Request.current().args.get("__UPLOADS");
                if (uploads == null) {
                    uploads = new ArrayList<Upload>();
                    Request.current().args.put("__UPLOADS", uploads);
                }
                try {
                    uploads.add(new FileUpload(fileItem));
                } catch (Exception e) {
                    // GAE does not support it, we try in memory
                    uploads.add(new MemoryUpload(fileItem));
                }
                putMapEntry(result, fileItem.getFieldName(), fileItem.getFieldName());
            }
        }
    } catch (FileUploadIOException e) {
        Logger.debug(e, "error");
        throw new IllegalStateException("Error when handling upload", e);
    } catch (IOException e) {
        Logger.debug(e, "error");
        throw new IllegalStateException("Error when handling upload", e);
    } catch (FileUploadException e) {
        Logger.debug(e, "error");
        throw new IllegalStateException("Error when handling upload", e);
    } catch (Exception e) {
        Logger.debug(e, "error");
        throw new UnexpectedException(e);
    }
    return result;
}

From source file:Project.FileUploadServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   ww  w .j a v  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 {
    //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:Project.FileUploadServlet.java

public static boolean processFile(String path, FileItemStream item) {
    try {//from  w w w .  ja  v a2 s.  c  o  m
        File f = new File(path + File.separator + "images");
        if (!f.exists()) {
            f.mkdir();
        }
        File savedFile = new File(f.getAbsolutePath() + File.separator + item.getName());
        FileOutputStream fos = new FileOutputStream(savedFile);
        InputStream is = item.openStream();
        int x = 0;
        byte[] b = new byte[1024];
        while ((x = is.read(b)) != -1) {
            fos.write(b, 0, x);
        }
        fos.flush();
        fos.close();
        return true;
    } catch (Exception e) {
        return false;
    }
}

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 {/*  ww  w. j a va  2s  . c  om*/
        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 w w  .  j av  a 2s . 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 {
    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
     */
}