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

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

Introduction

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

Prototype

String getName();

Source Link

Document

Returns the original filename in the client's filesystem, as provided by the browser (or other client software).

Usage

From source file:com.oprisnik.semdroid.SemdroidServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.info("doPost");
    StringBuilder sb = new StringBuilder();
    try {/*  ww w. j  av a 2 s. co m*/
        ServletFileUpload upload = new ServletFileUpload();
        // set max size (-1 for unlimited size)
        upload.setSizeMax(1024 * 1024 * 30); // 30MB
        upload.setHeaderEncoding("UTF-8");

        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                // Process regular form fields
                // String fieldname = item.getFieldName();
                // String fieldvalue = item.getString();
                // log.info("Got form field: " + fieldname + " " + fieldvalue);
            } else {
                // Process form file field (input type="file").
                String fieldname = item.getFieldName();
                String filename = FilenameUtils.getBaseName(item.getName());
                log.info("Got file: " + filename);
                InputStream filecontent = null;
                try {
                    filecontent = item.openStream();
                    // analyze
                    String txt = analyzeApk(filecontent);
                    if (txt != null) {
                        sb.append(txt);
                    } else {
                        sb.append("Error. Could not analyze ").append(filename);
                    }
                    log.info("Analysis done!");
                } finally {
                    if (filecontent != null) {
                        filecontent.close();
                    }
                }
            }
        }
        response.getWriter().print(sb.toString());
    } catch (FileUploadException e) {
        throw new ServletException("Cannot parse multipart request.", e);
    } catch (Exception ex) {
        log.warning("Exception: " + ex.getMessage());
        log.throwing(this.getClass().getName(), "doPost", ex);
    }

}

From source file:com.smartgwt.extensions.fileuploader.server.TestServiceImpl.java

private void processFiles(HttpServletRequest request, HttpServletResponse response) {
    HashMap<String, String> args = new HashMap<String, String>();
    try {// w  ww.  j a  va 2s .  c om
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        FileItemStream fileItem = null;
        // pick up parameters first and note actual FileItem
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            if (item.isFormField()) {
                args.put(name, Streams.asString(item.openStream()));
            } else {
                fileItem = item;
            }
        }
        if (fileItem != null) {
            args.put("contentType", fileItem.getContentType());
            args.put("fileName", FileUtils.filename(fileItem.getName()));
            System.out.println("uploading args " + args);
            String context = args.get("context");
            String model = args.get("model");
            String xq = args.get("xq");
            System.out.println(context + "," + model + "," + xq);
            File f = new File(args.get("fileName"));
            System.out.println(f.getAbsolutePath());
            /*
             * TODO: pboysen get the state, context and fileManager and store the
             * stream in fileName.  Parameters should be passed to locate state 
             * and conversion options.
             */
            response.setContentType("text/html");
            response.setHeader("Pragma", "No-cache");
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-cache");
            PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<body>");
            out.println("<script>");
            out.println("top.uploadComplete('" + args.get("fileName") + "');");
            out.println("</script>");
            out.println("</body>");
            out.println("</html>");
            out.flush();
        } else {
            //TODO: add error code
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:ai.baby.servlets.GenericFileGrabber.java

private Return<File> processFileUploadRequest(final FileItemIterator iter, final HttpSession session)
        throws IOException, FileUploadException {
    String returnVal = "Sorry! No Items To Process";
    final Map<String, String> parameterMap = new HashMap<String, String>();
    final File tempFile = getTempFile();
    String userFileExtension = null;

    while (iter.hasNext()) {
        final FileItemStream item = iter.next();
        final String paramName = item.getFieldName();
        final InputStream stream = item.openStream();

        if (item.isFormField()) {//Parameter-Value
            final String paramValue = Streams.asString(stream);
            parameterMap.put(paramName, paramValue);
        }/*from  w w w.j  a  v  a 2s  . co m*/
        if (!item.isFormField()) {
            final String usersFileName = item.getName();
            final int extensionDotIndex = usersFileName.lastIndexOf(".");
            userFileExtension = usersFileName.substring(extensionDotIndex + 1);
            final FileOutputStream fos = new FileOutputStream(tempFile);
            int byteCount = 0;
            while (true) {
                final int dataByte = stream.read();
                if (byteCount++ > UPLOAD_LIMIT) {
                    fos.close();
                    tempFile.delete();
                    return new ReturnImpl<File>(ExceptionCache.FILE_SIZE_EXCEPTION, "File Too Big!", true);
                }
                if (dataByte != -1) {
                    fos.write(dataByte);
                } else {
                    break;//break loop
                }
            }
            fos.close();
        }
    }

    final FileUploadListenerFace<File> fulf;

    /**
     * Implement this as a set of listeners. Why it wasn't done now is that, a new object of listener should be
     * created per request and added to the listener pool(list or array whatever).
     */
    switch (Integer.parseInt(parameterMap.get("type"))) {
    case 1:
        fulf = CDNProfilePhoto.getProfilePhotoCDNLocal();
        break;
    default:
        return new ReturnImpl<File>(ExceptionCache.UNSUPPORTED_SWITCH, "Unsupported Case", true);
    }
    if (tempFile == null) {
        return new ReturnImpl<File>(ExceptionCache.UNSUPPORTED_OPERATION_EXCEPTION, "No File!", true);
    }

    return fulf.run(tempFile, parameterMap, userFileExtension, session);
}

From source file:ai.ilikeplaces.servlets.GenericFileGrabber.java

private Return<File> processFileUploadRequest(final FileItemIterator iter, final HttpSession session)
        throws IOException, FileUploadException {
    String returnVal = "Sorry! No Items To Process";
    final Map<String, String> parameterMap = new HashMap<String, String>();
    final File tempFile = getTempFile();
    String userFileExtension = null;

    while (iter.hasNext()) {
        final FileItemStream item = iter.next();
        final String paramName = item.getFieldName();
        final InputStream stream = item.openStream();

        if (item.isFormField()) {//Parameter-Value
            final String paramValue = Streams.asString(stream);
            parameterMap.put(paramName, paramValue);
        }//from w  ww  .ja  v a 2s  . co m
        if (!item.isFormField()) {
            final String usersFileName = item.getName();
            final int extensionDotIndex = usersFileName.lastIndexOf(".");
            userFileExtension = usersFileName.substring(extensionDotIndex + 1);
            final FileOutputStream fos = new FileOutputStream(tempFile);
            int byteCount = 0;
            while (true) {
                final int dataByte = stream.read();
                if (byteCount++ > UPLOAD_LIMIT) {
                    fos.close();
                    tempFile.delete();
                    return new ReturnImpl<File>(ExceptionCache.FILE_SIZE_EXCEPTION, "File Too Big!", true);
                }
                if (dataByte != -1) {
                    fos.write(dataByte);
                } else {
                    break;//break loop
                }
            }
            fos.close();
        }
    }

    final FileUploadListenerFace<File> fulf;

    /**
     * Implement this as a set of listeners. Why it wasn't done now is that, a new object of listener should be
     * created per request and added to the listener pool(list or array whatever).
     */
    switch (Integer.parseInt(parameterMap.get("type"))) {
    case 1:
        fulf = CDNProfilePhoto.getProfilePhotoCDNLocal();
        break;
    case 2:
        fulf = CDNAlbumPrivateEvent.getAlbumPhotoCDNLocal();
        break;
    case 3:
        fulf = CDNAlbumTribe.getAlbumTribeCDNLocal();
        break;
    default:
        return new ReturnImpl<File>(ExceptionCache.UNSUPPORTED_SWITCH, "Unsupported Case", true);
    }
    if (tempFile == null) {
        return new ReturnImpl<File>(ExceptionCache.UNSUPPORTED_OPERATION_EXCEPTION, "No File!", true);
    }

    return fulf.run(tempFile, parameterMap, userFileExtension, session);
}

From source file:com.liferay.faces.metal.component.inputfile.internal.InputFileDecoderCommonsImpl.java

@Override
public Map<String, List<UploadedFile>> decode(FacesContext facesContext, String location) {

    Map<String, List<UploadedFile>> uploadedFileMap = null;
    ExternalContext externalContext = facesContext.getExternalContext();
    String uploadedFilesFolder = getUploadedFilesFolder(externalContext, location);

    // Using the sessionId, determine a unique folder path and create the path if it does not exist.
    String sessionId = getSessionId(externalContext);

    // FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be
    // created properly.
    sessionId = sessionId.replaceAll("[^A-Za-z0-9]", " ");

    File uploadedFilesPath = new File(uploadedFilesFolder, sessionId);

    if (!uploadedFilesPath.exists()) {
        uploadedFilesPath.mkdirs();//from   ww  w  . j  av a2s. co  m
    }

    // Initialize commons-fileupload with the file upload path.
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    diskFileItemFactory.setRepository(uploadedFilesPath);

    // Initialize commons-fileupload so that uploaded temporary files are not automatically deleted.
    diskFileItemFactory.setFileCleaningTracker(null);

    // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk
    // instead of staying in memory.
    diskFileItemFactory.setSizeThreshold(0);

    // Determine the max file upload size threshold (in bytes).
    int uploadedFileMaxSize = WebConfigParam.UploadedFileMaxSize.getIntegerValue(externalContext);

    // Parse the request parameters and save all uploaded files in a map.
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    servletFileUpload.setFileSizeMax(uploadedFileMaxSize);
    uploadedFileMap = new HashMap<String, List<UploadedFile>>();

    UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) FactoryExtensionFinder
            .getFactory(UploadedFileFactory.class);

    // Begin parsing the request for file parts:
    try {
        FileItemIterator fileItemIterator = null;

        HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest();
        fileItemIterator = servletFileUpload.getItemIterator(httpServletRequest);

        if (fileItemIterator != null) {

            int totalFiles = 0;

            // For each field found in the request:
            while (fileItemIterator.hasNext()) {

                try {
                    totalFiles++;

                    // Get the stream of field data from the request.
                    FileItemStream fieldStream = (FileItemStream) fileItemIterator.next();

                    // Get field name from the field stream.
                    String fieldName = fieldStream.getFieldName();

                    // Get the content-type, and file-name from the field stream.
                    String contentType = fieldStream.getContentType();
                    boolean formField = fieldStream.isFormField();

                    String fileName = null;

                    try {
                        fileName = fieldStream.getName();
                    } catch (InvalidFileNameException e) {
                        fileName = e.getName();
                    }

                    // Copy the stream of file data to a temporary file. NOTE: This is necessary even if the
                    // current field is a simple form-field because the call below to diskFileItem.getString()
                    // will fail otherwise.
                    DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName,
                            contentType, formField, fileName);
                    Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true);

                    // If the current field is a file, then
                    if (!diskFileItem.isFormField()) {

                        // Get the location of the temporary file that was copied from the request.
                        File tempFile = diskFileItem.getStoreLocation();

                        // If the copy was successful, then
                        if (tempFile.exists()) {

                            // Copy the commons-fileupload temporary file to a file in the same temporary
                            // location, but with the filename provided by the user in the upload. This has two
                            // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying
                            // the file, the developer can have access to a semi-permanent file, because the
                            // commmons-fileupload DiskFileItem.finalize() method automatically deletes the
                            // temporary one.
                            String tempFileName = tempFile.getName();
                            String tempFileAbsolutePath = tempFile.getAbsolutePath();

                            String copiedFileName = stripIllegalCharacters(fileName);

                            String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName,
                                    copiedFileName);
                            File copiedFile = new File(copiedFileAbsolutePath);
                            FileUtils.copyFile(tempFile, copiedFile);

                            // If present, build up a map of headers.
                            Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
                            FileItemHeaders fileItemHeaders = fieldStream.getHeaders();

                            if (fileItemHeaders != null) {
                                Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames();

                                if (headerNameItr != null) {

                                    while (headerNameItr.hasNext()) {
                                        String headerName = headerNameItr.next();
                                        Iterator<String> headerValuesItr = fileItemHeaders
                                                .getHeaders(headerName);
                                        List<String> headerValues = new ArrayList<String>();

                                        if (headerValuesItr != null) {

                                            while (headerValuesItr.hasNext()) {
                                                String headerValue = headerValuesItr.next();
                                                headerValues.add(headerValue);
                                            }
                                        }

                                        headersMap.put(headerName, headerValues);
                                    }
                                }
                            }

                            // Put a valid UploadedFile instance into the map that contains all of the
                            // uploaded file's attributes, along with a successful status.
                            Map<String, Object> attributeMap = new HashMap<String, Object>();
                            String id = Long.toString(((long) hashCode()) + System.currentTimeMillis());
                            String message = null;
                            UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(
                                    copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(),
                                    diskFileItem.getContentType(), headersMap, id, message, fileName,
                                    diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED);

                            addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName,
                                    fileName);
                        } else {

                            if ((fileName != null) && (fileName.trim().length() > 0)) {
                                Exception e = new IOException("Failed to copy the stream of uploaded file=["
                                        + fileName
                                        + "] to a temporary file (possibly a zero-length uploaded file)");
                                UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                                addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(e);

                    UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                    String fieldName = Integer.toString(totalFiles);
                    addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                }
            }
        }
    }

    // If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in
    // the map so that the developer can have some idea that something went wrong.
    catch (Exception e) {
        logger.error(e);

        UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
        addUploadedFile(uploadedFileMap, "unknown", uploadedFile);
    }

    return uploadedFileMap;
}

From source file:com.liferay.faces.alloy.component.inputfile.internal.InputFileDecoderCommonsImpl.java

@Override
public Map<String, List<UploadedFile>> decode(FacesContext facesContext, String location) {

    Map<String, List<UploadedFile>> uploadedFileMap = null;
    ExternalContext externalContext = facesContext.getExternalContext();
    String uploadedFilesFolder = getUploadedFilesFolder(externalContext, location);

    // Using the sessionId, determine a unique folder path and create the path if it does not exist.
    String sessionId = getSessionId(externalContext);

    // FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be
    // created properly.
    sessionId = sessionId.replaceAll("[^A-Za-z0-9]", " ");

    File uploadedFilesPath = new File(uploadedFilesFolder, sessionId);

    if (!uploadedFilesPath.exists()) {
        uploadedFilesPath.mkdirs();//from  w w  w  . j  a v  a  2s . c  om
    }

    // Initialize commons-fileupload with the file upload path.
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    diskFileItemFactory.setRepository(uploadedFilesPath);

    // Initialize commons-fileupload so that uploaded temporary files are not automatically deleted.
    diskFileItemFactory.setFileCleaningTracker(null);

    // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk
    // instead of staying in memory.
    diskFileItemFactory.setSizeThreshold(0);

    // Determine the max file upload size threshold (in bytes).
    int uploadedFileMaxSize = WebConfigParam.UploadedFileMaxSize.getIntegerValue(externalContext);

    // Parse the request parameters and save all uploaded files in a map.
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    servletFileUpload.setFileSizeMax(uploadedFileMaxSize);
    uploadedFileMap = new HashMap<String, List<UploadedFile>>();

    UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) FactoryExtensionFinder
            .getFactory(externalContext, UploadedFileFactory.class);

    // Begin parsing the request for file parts:
    try {
        FileItemIterator fileItemIterator = null;

        HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest();
        fileItemIterator = servletFileUpload.getItemIterator(httpServletRequest);

        if (fileItemIterator != null) {

            int totalFiles = 0;

            // For each field found in the request:
            while (fileItemIterator.hasNext()) {

                try {
                    totalFiles++;

                    // Get the stream of field data from the request.
                    FileItemStream fieldStream = (FileItemStream) fileItemIterator.next();

                    // Get field name from the field stream.
                    String fieldName = fieldStream.getFieldName();

                    // Get the content-type, and file-name from the field stream.
                    String contentType = fieldStream.getContentType();
                    boolean formField = fieldStream.isFormField();

                    String fileName = null;

                    try {
                        fileName = fieldStream.getName();
                    } catch (InvalidFileNameException e) {
                        fileName = e.getName();
                    }

                    // Copy the stream of file data to a temporary file. NOTE: This is necessary even if the
                    // current field is a simple form-field because the call below to diskFileItem.getString()
                    // will fail otherwise.
                    DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName,
                            contentType, formField, fileName);
                    Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true);

                    // If the current field is a file, then
                    if (!diskFileItem.isFormField()) {

                        // Get the location of the temporary file that was copied from the request.
                        File tempFile = diskFileItem.getStoreLocation();

                        // If the copy was successful, then
                        if (tempFile.exists()) {

                            // Copy the commons-fileupload temporary file to a file in the same temporary
                            // location, but with the filename provided by the user in the upload. This has two
                            // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying
                            // the file, the developer can have access to a semi-permanent file, because the
                            // commmons-fileupload DiskFileItem.finalize() method automatically deletes the
                            // temporary one.
                            String tempFileName = tempFile.getName();
                            String tempFileAbsolutePath = tempFile.getAbsolutePath();

                            String copiedFileName = stripIllegalCharacters(fileName);

                            String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName,
                                    copiedFileName);
                            File copiedFile = new File(copiedFileAbsolutePath);
                            FileUtils.copyFile(tempFile, copiedFile);

                            // If present, build up a map of headers.
                            Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
                            FileItemHeaders fileItemHeaders = fieldStream.getHeaders();

                            if (fileItemHeaders != null) {
                                Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames();

                                if (headerNameItr != null) {

                                    while (headerNameItr.hasNext()) {
                                        String headerName = headerNameItr.next();
                                        Iterator<String> headerValuesItr = fileItemHeaders
                                                .getHeaders(headerName);
                                        List<String> headerValues = new ArrayList<String>();

                                        if (headerValuesItr != null) {

                                            while (headerValuesItr.hasNext()) {
                                                String headerValue = headerValuesItr.next();
                                                headerValues.add(headerValue);
                                            }
                                        }

                                        headersMap.put(headerName, headerValues);
                                    }
                                }
                            }

                            // Put a valid UploadedFile instance into the map that contains all of the
                            // uploaded file's attributes, along with a successful status.
                            Map<String, Object> attributeMap = new HashMap<String, Object>();
                            String id = Long.toString(((long) hashCode()) + System.currentTimeMillis());
                            String message = null;
                            UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(
                                    copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(),
                                    diskFileItem.getContentType(), headersMap, id, message, fileName,
                                    diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED);

                            addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName,
                                    fileName);
                        } else {

                            if ((fileName != null) && (fileName.trim().length() > 0)) {
                                Exception e = new IOException("Failed to copy the stream of uploaded file=["
                                        + fileName
                                        + "] to a temporary file (possibly a zero-length uploaded file)");
                                UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                                addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(e);

                    UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                    String fieldName = Integer.toString(totalFiles);
                    addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                }
            }
        }
    }

    // If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in
    // the map so that the developer can have some idea that something went wrong.
    catch (Exception e) {
        logger.error(e);

        UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
        addUploadedFile(uploadedFileMap, "unknown", uploadedFile);
    }

    return uploadedFileMap;
}

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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  ww w  . jav  a 2  s.c  om
 *
 * @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:controllers.PictureController.java

@FilterWith(SecureFilter.class)
public Result uploadFinish(@LoggedInUser String username, Context context) throws Exception {
    String fileLocation = "";
    // Make sure the context really is a multipart context...
    if (context.isMultipart()) {
        Picture pic = new Picture();
        // 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 (item.isFormField()) {
                String value = Streams.asString(stream);
                switch (name) {
                case "name":
                    pic.setName(value);// w w w  .  j  a  va 2  s .  com
                    break;
                case "about":
                    pic.setAbout(value);
                    break;
                }

            } else {
                OutputStream outputStream = null;

                try {
                    fileLocation = "public/pictures/" + item.getName();
                    outputStream = new FileOutputStream(new File(fileLocation));

                    int read = 0;
                    byte[] bytes = new byte[1024];

                    while ((read = stream.read(bytes)) != -1) {
                        outputStream.write(bytes, 0, read);
                    }
                    pic.setFile(item.getName());

                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (stream != null) {
                        try {
                            stream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (outputStream != null) {
                        try {
                            // outputStream.flush();
                            outputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
        }
        pictureDao.postArticlePicture(username, pic);
    }

    reziseImage(fileLocation);
    // We always return ok. You don't want to do that in production ;)
    return Results.redirect("/picture/all");

}

From source file:com.newatlanta.appengine.servlet.GaeVfsServlet.java

/**
 * Writes the uploaded file to the GAE virtual file system (GaeVFS). Copied from:
 * //from  w w  w.j  a v  a2  s .com
 *      http://code.google.com/appengine/kb/java.html#fileforms
 * 
 * The "path" form parameter specifies a <a href="http://code.google.com/p/gaevfs/wiki/CombinedLocalOption"
 * target="_blank">GaeVFS path</a>. All directories within the path hierarchy
 * are created (if they don't already exist) when the file is saved.
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    // Check that we have a file upload request
    if (!ServletFileUpload.isMultipartContent(req)) {
        res.sendError(SC_BAD_REQUEST, "form enctype not multipart/form-data");
    }
    try {
        String path = "/";
        int blockSize = 0;
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iterator = upload.getItemIterator(req);

        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            if (item.isFormField()) {
                if (item.getFieldName().equalsIgnoreCase("path")) {
                    path = asString(item.openStream());
                    if (!path.endsWith("/")) {
                        path = path + "/";
                    }
                } else if (item.getFieldName().equalsIgnoreCase("blocksize")) {
                    String s = asString(item.openStream());
                    if (s.length() > 0) {
                        blockSize = Integer.parseInt(s);
                    }
                }
            } else {
                Path filePath = Paths.get(path + item.getName());
                Path parent = filePath.getParent();
                if (parent.notExists()) {
                    createDirectories(parent);
                }
                if (blockSize > 0) {
                    filePath.createFile(withBlockSize(blockSize));
                } else {
                    filePath.createFile();
                }
                // IOUtils.copy() buffers the InputStream internally
                OutputStream out = new BufferedOutputStream(filePath.newOutputStream(), BUFF_SIZE);
                copy(item.openStream(), out);
                out.close();
            }
        }

        // redirect to the configured response, or to this servlet for a
        // directory listing
        res.sendRedirect(uploadRedirect != null ? uploadRedirect : path);

    } catch (FileUploadException e) {
        throw new ServletException(e);
    }
}

From source file:com.manydesigns.portofino.stripes.StreamingCommonsMultipartWrapper.java

/**
 * Pseudo-constructor that allows the class to perform any initialization necessary.
 *
 * @param request     an HttpServletRequest that has a content-type of multipart.
 * @param tempDir a File representing the temporary directory that can be used to store
 *        file parts as they are uploaded if this is desirable
 * @param maxPostSize the size in bytes beyond which the request should not be read, and a
 *                    FileUploadLimitExceeded exception should be thrown
 * @throws IOException if a problem occurs processing the request of storing temporary
 *                    files//from   w w  w. ja  va 2 s .c  om
 * @throws FileUploadLimitExceededException if the POST content is longer than the
 *                     maxPostSize supplied.
 */
@SuppressWarnings("unchecked")
public void build(HttpServletRequest request, File tempDir, long maxPostSize)
        throws IOException, FileUploadLimitExceededException {
    try {
        this.charset = request.getCharacterEncoding();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(tempDir);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxPostSize);
        FileItemIterator iterator = upload.getItemIterator(request);

        Map<String, List<String>> params = new HashMap<String, List<String>>();

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

            // If it's a form field, add the string value to the list
            if (item.isFormField()) {
                List<String> values = params.get(item.getFieldName());
                if (values == null) {
                    values = new ArrayList<String>();
                    params.put(item.getFieldName(), values);
                }
                values.add(charset == null ? IOUtils.toString(stream) : IOUtils.toString(stream, charset));
            }
            // Else store the file param
            else {
                TempFile tempFile = TempFileService.getInstance().newTempFile(item.getContentType(),
                        item.getName());
                int size = IOUtils.copy(stream, tempFile.getOutputStream());
                FileItem fileItem = new FileItem(item.getName(), item.getContentType(), tempFile, size);
                files.put(item.getFieldName(), fileItem);
            }
        }

        // Now convert them down into the usual map of String->String[]
        for (Map.Entry<String, List<String>> entry : params.entrySet()) {
            List<String> values = entry.getValue();
            this.parameters.put(entry.getKey(), values.toArray(new String[values.size()]));
        }
    } catch (FileUploadBase.SizeLimitExceededException slee) {
        throw new FileUploadLimitExceededException(maxPostSize, slee.getActualSize());
    } catch (FileUploadException fue) {
        IOException ioe = new IOException("Could not parse and cache file upload data.");
        ioe.initCause(fue);
        throw ioe;
    }

}