Example usage for org.apache.commons.fileupload.servlet ServletFileUpload getItemIterator

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload getItemIterator

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload getItemIterator.

Prototype

public FileItemIterator getItemIterator(HttpServletRequest request) throws FileUploadException, IOException 

Source Link

Document

Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a> compliant <code>multipart/form-data</code> stream.

Usage

From source file:com.cognifide.aet.executor.SuiteServlet.java

private Map<String, String> getRequestData(HttpServletRequest request) {
    Map<String, String> requestData = new HashMap<>();

    ServletFileUpload upload = new ServletFileUpload();
    try {//from   w  w  w  .j  a  v a  2s.co m
        FileItemIterator itemIterator = upload.getItemIterator(request);
        while (itemIterator.hasNext()) {
            FileItemStream item = itemIterator.next();
            InputStream itemStream = item.openStream();
            String value = Streams.asString(itemStream, CharEncoding.UTF_8);
            requestData.put(item.getFieldName(), value);
        }
    } catch (FileUploadException | IOException e) {
        LOGGER.error("Failed to process request", e);
    }

    return requestData;
}

From source file:com.google.appinventor.server.UploadServlet.java

private InputStream getRequestStream(HttpServletRequest req, String expectedFieldName) throws Exception {
    ServletFileUpload upload = new ServletFileUpload();
    FileItemIterator iterator = upload.getItemIterator(req);
    while (iterator.hasNext()) {
        FileItemStream item = iterator.next();
        if (item.getFieldName().equals(expectedFieldName)) {
            return item.openStream();
        }/*  w ww.jav  a2  s.c o  m*/
    }

    throw new IllegalArgumentException("Field " + expectedFieldName + " not found in upload");
}

From source file:jetbrick.web.mvc.multipart.CommonsFileUpload.java

@Override
public MultipartRequest transform(HttpServletRequest request) throws IOException {
    String contextType = request.getHeader("Content-Type");
    if (contextType == null || !contextType.startsWith("multipart/form-data")) {
        return null;
    }/*  w ww . j a  v a 2s.c  om*/

    String encoding = request.getCharacterEncoding();

    MultipartRequest req = new MultipartRequest(request);
    ServletFileUpload upload = new ServletFileUpload();
    upload.setHeaderEncoding(encoding);

    try {
        FileItemIterator it = upload.getItemIterator(request);
        while (it.hasNext()) {
            FileItemStream item = it.next();
            String fieldName = item.getFieldName();
            InputStream stream = item.openStream();
            try {
                if (item.isFormField()) {
                    req.setParameter(fieldName, Streams.asString(stream, encoding));
                } else {
                    String originalFilename = item.getName();
                    if (originalFilename == null || originalFilename.length() == 0) {
                        continue;
                    }
                    File diskFile = UploadUtils.getUniqueTemporaryFile(originalFilename);
                    OutputStream fos = new FileOutputStream(diskFile);

                    try {
                        IoUtils.copy(stream, fos);
                    } finally {
                        IoUtils.closeQuietly(fos);
                    }

                    FilePart filePart = new FilePart(fieldName, originalFilename, diskFile);
                    req.addFile(filePart);
                }
            } finally {
                IoUtils.closeQuietly(stream);
            }
        }
    } catch (FileUploadException e) {
        throw new IllegalStateException(e);
    }

    return req;
}

From source file:br.com.ifpb.bdnc.projeto.geo.servlets.CadastraImagem.java

private Image mountImage(HttpServletRequest request) {
    Image image = new Image();
    image.setCoord(new Coordenate());
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();
        try {/*from   w  w  w.  ja  va  2  s  .c  o m*/
            FileItemIterator itr = upload.getItemIterator(request);
            while (itr.hasNext()) {
                FileItemStream item = itr.next();
                if (item.isFormField()) {
                    InputStream in = item.openStream();
                    byte[] b = new byte[in.available()];
                    in.read(b);
                    if (item.getFieldName().equals("description")) {
                        image.setDescription(new String(b));
                    } else if (item.getFieldName().equals("authors")) {
                        image.setAuthors(new String(b));
                    } else if (item.getFieldName().equals("end")) {
                        image.setDate(
                                LocalDate.parse(new String(b), DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                    } else if (item.getFieldName().equals("latitude")) {
                        image.getCoord().setLat(new String(b));
                    } else if (item.getFieldName().equals("longitude")) {
                        image.getCoord().setLng(new String(b));
                    } else if (item.getFieldName().equals("heading")) {
                        image.getCoord().setHeading(new String(b));
                    } else if (item.getFieldName().equals("pitch")) {
                        image.getCoord().setPitch(new String(b));
                    } else if (item.getFieldName().equals("zoom")) {
                        image.getCoord().setZoom(new String(b));
                    }
                } else {
                    if (!item.getName().equals("")) {
                        MultipartData md = new MultipartData();
                        String folder = "historicImages";
                        md.setFolder(folder);
                        String path = request.getServletContext().getRealPath("/");
                        System.out.println(path);
                        String nameToSave = "pubImage" + Calendar.getInstance().getTimeInMillis()
                                + item.getName();
                        image.setImagePath(folder + "/" + nameToSave);
                        md.saveImage(path, item, nameToSave);
                        String imageMinPath = folder + "/" + "min" + nameToSave;
                        RedimencionadorImagem.resize(path, folder + "/" + nameToSave,
                                path + "/" + imageMinPath.toString(), IMAGE_MIN_WIDTH, IMAGE_MIM_HEIGHT);
                        image.setMinImagePath(imageMinPath);
                    }
                }
            }
        } catch (FileUploadException | IOException ex) {
            System.out.println("Erro ao manipular dados");
        }
    }
    return image;
}

From source file:com.anritsu.mcreleaseportal.utils.FileUpload.java

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

    HttpSession session = request.getSession();
    session.setAttribute("mcPackage", null);
    PrintWriter pw = response.getWriter();
    response.setContentType("text/plain");
    ServletFileUpload upload = new ServletFileUpload();
    try {
        FileItemIterator iter = upload.getItemIterator(request);

        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            InputStream stream = item.openStream();

            // Save input stream file for later use
            File dir = new File(Configuration.getInstance().getSavePath());
            if (!dir.exists() && !dir.isDirectory()) {
                dir.mkdir();
                LOGGER.log(Level.INFO, "Changes.xml archive directory was created at " + dir.getAbsolutePath());
            }
            String fileName = request.getSession().getId() + "_" + System.currentTimeMillis();
            File file = new File(dir, fileName);
            file.createNewFile();
            Path path = file.toPath();
            Files.copy(stream, path, StandardCopyOption.REPLACE_EXISTING);
            LOGGER.log(Level.INFO, "changes.xml saved on disk as: " + file.getAbsolutePath());

            // Save filename to session for next calls
            session.setAttribute("xmlFileLocation", file.getAbsolutePath());
            LOGGER.log(Level.INFO, "changes.xml saved on session as: fileName:" + file.getAbsolutePath());

            // Cleanup
            stream.close();

        }

    } catch (FileUploadException | IOException | RuntimeException e) {
        pw.println(
                "An error occurred when trying to process uploaded file! \n Please check the file consistency and try to re-submit. \n If the error persist pleace contact system administrator!");
    }
}

From source file:com.google.appinventor.server.GalleryServlet.java

private InputStream getRequestStream(HttpServletRequest req, String expectedFieldName) throws Exception {
    ServletFileUpload upload = new ServletFileUpload();
    FileItemIterator iterator = upload.getItemIterator(req);
    while (iterator.hasNext()) {
        FileItemStream item = iterator.next();
        //      LOG.info(item.getContentType());
        if (item.getFieldName().equals(expectedFieldName)) {
            return item.openStream();
        }//from   w  w w.  j  a v  a2  s  .com
    }
    throw new IllegalArgumentException("Field " + expectedFieldName + " not found in upload");
}

From source file:edu.caltech.ipac.firefly.server.servlets.AnyFileUpload.java

protected void processRequest(HttpServletRequest req, HttpServletResponse res) throws Exception {

    String dest = req.getParameter(DEST_PARAM);
    String preload = req.getParameter(PRELOAD_PARAM);
    String overrideCacheKey = req.getParameter(CACHE_KEY);
    String fileType = req.getParameter(FILE_TYPE);

    if (!ServletFileUpload.isMultipartContent(req)) {
        sendReturnMsg(res, 400, "Is not a Multipart request. Request rejected.", "");
    }/*from   w  w w  . j av a 2s  .c o m*/
    StopWatch.getInstance().start("Upload File");

    ServletFileUpload upload = new ServletFileUpload();
    FileItemIterator iter = upload.getItemIterator(req);
    while (iter.hasNext()) {
        FileItemStream item = iter.next();

        if (!item.isFormField()) {
            String fileName = item.getName();
            InputStream inStream = new BufferedInputStream(item.openStream(),
                    IpacTableUtil.FILE_IO_BUFFER_SIZE);
            String ext = resolveExt(fileName);
            FileType fType = resolveType(fileType, ext, item.getContentType());
            File destDir = resolveDestDir(dest, fType);
            boolean doPreload = resolvePreload(preload, fType);

            File uf = File.createTempFile("upload_", ext, destDir);
            String rPathInfo = ServerContext.replaceWithPrefix(uf);

            UploadFileInfo fi = new UploadFileInfo(rPathInfo, uf, fileName, item.getContentType());
            String fileCacheKey = overrideCacheKey != null ? overrideCacheKey : rPathInfo;
            UserCache.getInstance().put(new StringKey(fileCacheKey), fi);

            if (doPreload && fType == FileType.FITS) {
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(uf),
                        IpacTableUtil.FILE_IO_BUFFER_SIZE);
                TeeInputStream tee = new TeeInputStream(inStream, bos);
                try {
                    final Fits fits = new Fits(tee);
                    FitsRead[] frAry = FitsRead.createFitsReadArray(fits);
                    FitsCacher.addFitsReadToCache(uf, frAry);
                } finally {
                    FileUtil.silentClose(bos);
                    FileUtil.silentClose(tee);
                }
            } else {
                FileUtil.writeToFile(inStream, uf);
            }
            sendReturnMsg(res, 200, null, fileCacheKey);
            Counters.getInstance().increment(Counters.Category.Upload, fi.getContentType());
            return;
        }
    }
    StopWatch.getInstance().printLog("Upload File");
}

From source file:br.edu.ifpb.sislivros.model.ProcessadorFotos.java

public String processarArquivo(HttpServletRequest request, String nameToSave)
        throws ServletException, IOException {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();
        try {/* w  w  w  .  ja  va2  s  .  co m*/
            FileItemIterator itr = upload.getItemIterator(request);

            while (itr.hasNext()) {
                FileItemStream item = itr.next();
                if (!item.isFormField()) {
                    //                        pode ser tb sem a barra ????
                    //                        String path = request.getServletContext().getRealPath("");
                    String contextPath = request.getServletContext().getRealPath("/");

                    //refatorar aqui apenas para salvarimagem receber um pasta, inputStream e o nome
                    //aqui, criar um inputStream atravs do arquivo item antes de enviar
                    //diminuir 1 mtodo, deixando salvarImagem mais genrico
                    if (salvarImagem(contextPath + File.separator + folder, item, nameToSave)) {
                        return folder + "/" + nameToSave;
                    }
                }
            }

        } catch (FileUploadException ex) {
            System.out.println("erro ao obter informaoes sobre o arquivo");
        }

    } else {
        System.out.println("Erro no formulario!");
    }

    return null;
}

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

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

    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  ww  w  . j  a  v  a2s.  co m

    String fileId = req.getParameter("sessionId").toString().trim();
    FileItemFactory factory = new ProgressMonitorFileItemFactory(req, fileId);
    ServletFileUpload upload = new ServletFileUpload();

    upload.setFileItemFactory(factory);

    try {
        // Parse the request

        FileItemIterator iter = upload.getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();

            if (!item.isFormField()) {
                String fullName = item.getName();
                int extensionInd = fullName.lastIndexOf(".");
                String fileName = fullName.substring(0, extensionInd);
                String extension = fullName.substring(extensionInd + 1);
                InputStream stream = item.openStream();

                BusinessDTO fileDTO = clientRequest.newSecureFile(fileName, extension, stream);

                // return the vault id to the dhtmlxVault callback
                req.getSession().setAttribute("FileUpload.Progress." + fileId, fileDTO.getId());
            }
        }
    } catch (FileUploadException e) {
        throw new FileWriteExceptionDTO(e.getLocalizedMessage());
    } catch (RuntimeException e) {
        req.getSession().setAttribute("FileUpload.Progress." + fileId, "fail: " + e.getLocalizedMessage());
    }
}

From source file:edu.morgan.server.UploadFile.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {
    // Check that we have a file upload request
    RequestDispatcher rd;//from   w w  w  . j ava  2s .c  om
    response.setContentType("text/html");

    isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
        rd = request.getRequestDispatcher("fail.jsp");
        rd.forward(request, response);
    }

    try {
        ServletFileUpload upload = new ServletFileUpload();
        response.setContentType("text/plain");

        FileItemIterator iterator = upload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream stream = item.openStream();
            this.read(stream);
        }
        request.removeAttribute("incompleteStudents");
        request.setAttribute("incompleteStudents", studentList);

        rd = request.getRequestDispatcher("Success");
        rd.forward(request, response);

    } catch (Exception ex) {
        throw new ServletException(ex);
    }

}