Example usage for org.apache.commons.fileupload.disk DiskFileItemFactory setSizeThreshold

List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory setSizeThreshold

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.disk DiskFileItemFactory setSizeThreshold.

Prototype

public void setSizeThreshold(int sizeThreshold) 

Source Link

Document

Sets the size threshold beyond which files are written directly to disk.

Usage

From source file:com.sourcesense.confluence.servlets.CMISProxyServlet.java

/**
 * Sets up the given {@link PostMethod} to send the same multipart POST
 * data as was sent in the given {@link HttpServletRequest}
 *
 * @param postMethodProxyRequest The {@link PostMethod} that we are
 *                               configuring to send a multipart POST request
 * @param httpServletRequest     The {@link HttpServletRequest} that contains
 *                               the mutlipart POST data to be sent via the {@link PostMethod}
 * @throws javax.servlet.ServletException If something fails when uploading the content to the server
 *//*  w  ww.  ja v a  2 s.  c  o  m*/
@SuppressWarnings({ "unchecked", "ToArrayCallWithZeroLengthArrayArgument" })
private void handleMultipartPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
        throws ServletException {
    // Create a factory for disk-based file items
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    // Set factory constraints
    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
    // Create a new file upload handler
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    // Parse the request
    try {
        // Get the multipart items as a list
        List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
        // Create a list to hold all of the parts
        List<Part> listParts = new ArrayList<Part>();
        // Iterate the multipart items list
        for (FileItem fileItemCurrent : listFileItems) {
            // If the current item is a form field, then create a string part
            if (fileItemCurrent.isFormField()) {
                StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name
                        fileItemCurrent.getString() // The field value
                );
                // Add the part to the list
                listParts.add(stringPart);
            } else {
                // The item is a file upload, so we create a FilePart
                FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name
                        new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name
                                fileItemCurrent.get() // The uploaded file contents
                        ));
                // Add the part to the list
                listParts.add(filePart);
            }
        }
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
                listParts.toArray(new Part[] {}), postMethodProxyRequest.getParams());
        postMethodProxyRequest.setRequestEntity(multipartRequestEntity);
        // The current content-type header (received from the client) IS of
        // type "multipart/form-data", but the content-type header also
        // contains the chunk boundary string of the chunks. Currently, this
        // header is using the boundary of the client request, since we
        // blindly copied all headers from the client request to the proxy
        // request. However, we are creating a new request with a new chunk
        // boundary string, so it is necessary that we re-set the
        // content-type string to reflect the new chunk boundary string
        postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME,
                multipartRequestEntity.getContentType());
    } catch (FileUploadException fileUploadException) {
        throw new ServletException(fileUploadException);
    }
}

From source file:com.twinsoft.convertigo.engine.servlets.GenericServlet.java

public Object processRequest(HttpServletRequest request) throws Exception {
    HttpServletRequestTwsWrapper twsRequest = request instanceof HttpServletRequestTwsWrapper
            ? (HttpServletRequestTwsWrapper) request
            : null;//from ww w  .j  ava  2s .  co  m
    File temporaryFile = null;

    try {
        // Check multipart request
        if (ServletFileUpload.isMultipartContent(request)) {
            Engine.logContext.debug("(ServletRequester.initContext) Multipart resquest");

            // Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();

            // Set factory constraints
            factory.setSizeThreshold(1000);

            temporaryFile = File.createTempFile("c8o-multipart-files", ".tmp");
            int cptFile = 0;
            temporaryFile.delete();
            temporaryFile.mkdirs();
            factory.setRepository(temporaryFile);
            Engine.logContext.debug("(ServletRequester.initContext) Temporary folder for upload is : "
                    + temporaryFile.getAbsolutePath());

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

            // Set overall request size constraint
            upload.setSizeMax(
                    EnginePropertiesManager.getPropertyAsLong(PropertyName.FILE_UPLOAD_MAX_REQUEST_SIZE));
            upload.setFileSizeMax(
                    EnginePropertiesManager.getPropertyAsLong(PropertyName.FILE_UPLOAD_MAX_FILE_SIZE));

            // Parse the request
            List<FileItem> items = GenericUtils.cast(upload.parseRequest(request));

            for (FileItem fileItem : items) {
                String parameterName = fileItem.getFieldName();
                String parameterValue;
                if (fileItem.isFormField()) {
                    parameterValue = fileItem.getString();
                    Engine.logContext.trace("(ServletRequester.initContext) Value for field '" + parameterName
                            + "' : " + parameterValue);
                } else {
                    String name = fileItem.getName().replaceFirst("^.*(?:\\\\|/)(.*?)$", "$1");
                    if (name.length() > 0) {
                        File wDir = new File(temporaryFile, "" + (++cptFile));
                        wDir.mkdirs();
                        File wFile = new File(wDir, name);
                        fileItem.write(wFile);
                        fileItem.delete();
                        parameterValue = wFile.getAbsolutePath();
                        Engine.logContext
                                .debug("(ServletRequester.initContext) Temporary uploaded file for field '"
                                        + parameterName + "' : " + parameterValue);
                    } else {
                        Engine.logContext
                                .debug("(ServletRequester.initContext) No temporary uploaded file for field '"
                                        + parameterName + "', empty name");
                        parameterValue = "";
                    }
                }

                if (twsRequest != null) {
                    twsRequest.addParameter(parameterName, parameterValue);
                }
            }
        }

        Requester requester = getRequester();
        request.setAttribute("convertigo.requester", requester);

        Object result = requester.processRequest(request);

        request.setAttribute("convertigo.cookies", requester.context.getCookieStrings());

        String trSessionId = requester.context.getSequenceTransactionSessionId();
        if (trSessionId != null) {
            request.setAttribute("sequence.transaction.sessionid", trSessionId);
        }

        if (requester.context.requireEndOfContext) {
            // request.setAttribute("convertigo.requireEndOfContext",
            // requester);
            request.setAttribute("convertigo.requireEndOfContext", Boolean.TRUE);
        }

        if (request.getAttribute("convertigo.contentType") == null) { // if
            // contentType
            // set by
            // webclipper
            // servlet
            // (#320)
            request.setAttribute("convertigo.contentType", requester.context.contentType);
        }

        request.setAttribute("convertigo.cacheControl", requester.context.cacheControl);
        request.setAttribute("convertigo.context.contextID", requester.context.contextID);
        request.setAttribute("convertigo.isErrorDocument", new Boolean(requester.context.isErrorDocument));
        request.setAttribute("convertigo.context.removalRequired",
                new Boolean(requester.context.removalRequired()));
        if (requester.context.requestedObject != null) { // #397 : charset HTTP
            // header missing
            request.setAttribute("convertigo.charset", requester.context.requestedObject.getEncodingCharSet());
        } else { // #3803
            Engine.logEngine.warn(
                    "(GenericServlet) requestedObject is null. Set encoding to UTF-8 for processRequest.");
            request.setAttribute("convertigo.charset", "UTF-8");
        }

        return result;
    } finally {
        if (temporaryFile != null) {
            try {
                Engine.logEngine.debug(
                        "(GenericServlet) Removing the temporary file : " + temporaryFile.getAbsolutePath());
                FileUtils.deleteDirectory(temporaryFile);
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.intranet.intr.proveedores.EmpControllerGestion.java

@RequestMapping(value = "EPfotoProveedor.htm", method = RequestMethod.POST)
public String fotoProveedor_post(@ModelAttribute("proveedor") proveedores prov, BindingResult result,
        HttpServletRequest request) {/*from   w w  w  .j ava2 s.c  o m*/
    String mensaje = "";
    //C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\fotosPerfil\\proveedores
    String ubicacionArchivo = "C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\fotosPerfil\\proveedores";
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1024);

    ServletFileUpload upload = new ServletFileUpload(factory);

    System.out.println("uPDAT FOTO ID proveedor: " + prov.getId());
    try {
        System.out.println("1: " + prov.getId());
        List<FileItem> partes = upload.parseRequest(request);
        for (FileItem item : partes) {
            System.out.println("2" + item.getName());
            File file = new File(ubicacionArchivo, item.getName());
            System.out.println("3" + prov.getId());
            item.write(file);
            System.out.println("4" + idProv);
            prov.setNombreFoto(item.getName());
            proveedoresService.UpdateImagen(prov);
            System.out.println("5: " + prov.getId());
        }
        System.out.println("Archi subido correctamente");
    } catch (Exception ex) {
        System.out.println("Error al subir archivo" + ex.getMessage());
    }

    //return "redirect:uploadFile.htm";

    return "redirect:EPGestion.htm";

}

From source file:com.intranet.intr.SupControllerInformacion.java

@RequestMapping(value = "fotoSupervisor.htm", method = RequestMethod.POST)
public String updateSecurityL_post(@ModelAttribute("empleado") empleados empleado, BindingResult result,
        HttpServletRequest request, Principal principal) {
    String mensaje = "";
    String ubicacionArchivo = "C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\fotosPerfil";
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1024);

    ServletFileUpload upload = new ServletFileUpload(factory);
    String name = principal.getName();
    empleados po = new empleados();

    try {/*from  ww w. ja  v  a 2  s  .c o  m*/
        List<FileItem> partes = upload.parseRequest(request);
        for (FileItem item : partes) {
            System.out.println("NOMBRE FOTO: " + item.getName());
            File file = new File(ubicacionArchivo, item.getName());
            item.write(file);
            users u = usuarioService.getByLogin(name);
            po = empleadoService.ByNif(u.getNif());
            po.setNombrefotografia(item.getName());
            empleadoService.UpdateImagen(po);
        }
        System.out.println("Archi subido correctamente");
    } catch (Exception ex) {
        System.out.println("Error al subir archivo" + ex.getMessage());
    }

    //return "redirect:uploadFile.htm";

    return "redirect:ActualizarfotoSupervisor.htm";

}

From source file:com.qlkh.client.server.proxy.ProxyServlet.java

/**
 * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same multipart POST
 * data as was sent in the given {@link javax.servlet.http.HttpServletRequest}
 *
 * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are
 *                               configuring to send a multipart POST request
 * @param httpServletRequest     The {@link javax.servlet.http.HttpServletRequest} that contains
 *                               the mutlipart POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod}
 *///from w  w w .  j  a v a2s .c om
@SuppressWarnings("unchecked")
private void handleMultipartPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
        throws ServletException {
    // Create a factory for disk-based file items
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    // Set factory constraints
    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
    // Create a new file upload handler
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    // Parse the request
    try {
        // Get the multipart items as a list
        List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
        // Create a list to hold all of the parts
        List<Part> listParts = new ArrayList<Part>();
        // Iterate the multipart items list
        for (FileItem fileItemCurrent : listFileItems) {
            // If the current item is a form field, then create a string part
            if (fileItemCurrent.isFormField()) {
                StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name
                        fileItemCurrent.getString() // The field value
                );
                // Add the part to the list
                listParts.add(stringPart);
            } else {
                // The item is a file upload, so we create a FilePart
                FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name
                        new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name
                                fileItemCurrent.get() // The uploaded file contents
                        ));
                // Add the part to the list
                listParts.add(filePart);
            }
        }
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
                listParts.toArray(new Part[] {}), postMethodProxyRequest.getParams());
        postMethodProxyRequest.setRequestEntity(multipartRequestEntity);
        // The current content-type header (received from the client) IS of
        // type "multipart/form-data", but the content-type header also
        // contains the chunk boundary string of the chunks. Currently, this
        // header is using the boundary of the client request, since we
        // blindly copied all headers from the client request to the proxy
        // request. However, we are creating a new request with a new chunk
        // boundary string, so it is necessary that we re-set the
        // content-type string to reflect the new chunk boundary string
        postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME,
                multipartRequestEntity.getContentType());
    } catch (FileUploadException fileUploadException) {
        throw new ServletException(fileUploadException);
    }
}

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   w w  w. j  ava 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(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 .ja v a  2s .c o 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(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:fr.cnes.sitools.ext.jeobrowser.upload.JeoUploadResource.java

/**
 * Upload a File contained in the given entity to the temporary folder of the
 * Sitools Server at the given directory name
 * //from ww w  .j av  a  2s  . c  o  m
 * @param entity
 *          the file to upload
 * @param directoryName
 *          the directory
 * @return a Representation
 * 
 */
private Representation uploadFile(Representation entity, String directoryName) {
    Representation rep = null;
    if (entity != null) {
        settings = ((SitoolsApplication) getApplication()).getSettings();
        File storeDirectory = new File(settings.getTmpFolderUrl() + "/" + directoryName);
        storeDirectory.mkdirs();

        if (MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {
            // storeDirectory = "c:\\temp\\";

            // The Apache FileUpload project parses HTTP requests which
            // conform to RFC 1867, "Form-based File Upload in HTML". That
            // is, if an HTTP request is submitted using the POST method,
            // and with a content type of "multipart/form-data", then
            // FileUpload can parse that request, and get all uploaded files
            // as FileItem.

            // 1/ Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1000240);

            // 2/ Create a new file upload handler based on the Restlet
            // FileUpload extension that will parse Restlet requests and
            // generates FileItems.
            RestletFileUpload upload = new RestletFileUpload(factory);

            List<FileItem> items;

            // 3/ Request is parsed by the handler which generates a
            // list of FileItems
            try {
                items = upload.parseRequest(getRequest());
            } catch (FileUploadException e1) {
                e1.printStackTrace();
                items = new ArrayList<FileItem>();
            }

            // Says if at least one file has been handled
            boolean found = false;
            // List the files that haven't been uploaded
            List<String> oops = new ArrayList<String>();
            // count the number files
            int nbFiles = 0;

            for (final Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem fi = it.next();
                // Process only the items that *really* contains an uploaded
                // file and save them on disk
                if (fi.getName() != null) {
                    found = true;
                    nbFiles++;
                    File file = new File(storeDirectory, fi.getName());
                    try {
                        fi.write(file);
                        filePath = file.getAbsolutePath();
                    } catch (Exception e) {
                        System.out.println(
                                "Can't write the content of " + file.getPath() + " due to " + e.getMessage());
                        oops.add(file.getName());
                    }
                } else {
                    // This is a simple text form input.
                    System.out.println(fi.getFieldName() + " " + fi.getString());
                }
            }

            // Once handled, you can send a report to the user.
            StringBuilder sb = new StringBuilder();
            if (found) {
                sb.append(nbFiles);
                if (nbFiles > 1) {
                    sb.append(" files sent");
                } else {
                    sb.append(" file sent");
                }
                if (!oops.isEmpty()) {
                    sb.append(", ").append(oops.size());
                    if (oops.size() > 1) {
                        sb.append(" files in error:");
                    } else {
                        sb.append(" file in error:");
                    }
                    for (int i = 0; i < oops.size(); i++) {
                        if (i > 0) {
                            sb.append(",");
                        }
                        sb.append(" \"").append(oops.get(i)).append("\"");
                    }
                }
                sb.append(".");
                rep = new StringRepresentation(sb.toString(), MediaType.TEXT_PLAIN);
            } else {
                // Some problem occurs, sent back a simple line of text.
                rep = new StringRepresentation("no file uploaded", MediaType.TEXT_PLAIN);
            }
        } else {
            String fileName = "tmp_zip.zip";
            String resourceRef = RIAPUtils.getRiapBase() + settings.getString(Consts.APP_TMP_FOLDER_URL) + "/"
                    + directoryName + "/" + fileName;
            filePath = settings.getTmpFolderUrl() + "/" + directoryName + "/" + fileName;
            // Transfer of PUT calls is only allowed if the readOnly flag is
            // not set.
            Request contextRequest = new Request(Method.PUT, resourceRef);

            // Add support of partial PUT calls.
            contextRequest.getRanges().addAll(getRanges());
            contextRequest.setEntity(entity);

            org.restlet.Response contextResponse = new org.restlet.Response(contextRequest);
            contextRequest.setResourceRef(resourceRef);
            getContext().getClientDispatcher().handle(contextRequest, contextResponse);
            setStatus(contextResponse.getStatus());

        }
    } else {
        // POST request with no entity.
        getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
    }
    return rep;
}

From source file:com.buddycloud.mediaserver.business.dao.MediaDAO.java

/**
 * Uploads media./*from   w  w  w  .  jav a 2s. co  m*/
 * @param userId user that is uploading the media.
 * @param entityId channel where the media will belong.
 * @param request media file and required upload fields.
 * @param isAvatar if the media to be uploaded is an avatar.
 * @return media's metadata, if the upload ends with success
 * @throws FileUploadException the is something wrong with the request.
 * @throws UserNotAllowedException the user {@link userId} is now allowed to upload media in this channel.
 */
public String insertFormDataMedia(String userId, String entityId, Request request, boolean isAvatar)
        throws FileUploadException, UserNotAllowedException {

    LOGGER.debug("User '" + userId + "' trying to upload form-data media in: " + entityId);

    boolean isUserAllowed = pubsub.matchUserCapability(userId, entityId,
            new OwnerDecorator(new ModeratorDecorator(new PublisherDecorator())));

    if (!isUserAllowed) {
        LOGGER.debug("User '" + userId + "' not allowed to upload file in: " + entityId);
        throw new UserNotAllowedException(userId);
    }

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(
            Integer.valueOf(configuration.getProperty(MediaServerConfiguration.MEDIA_SIZE_LIMIT_PROPERTY)));

    List<FileItem> items = null;

    try {
        RestletFileUpload upload = new RestletFileUpload(factory);
        items = upload.parseRequest(request);
    } catch (Throwable e) {
        throw new FileUploadException("Invalid request data.");
    }

    // get form fields
    String fileName = getFormFieldContent(items, Constants.NAME_FIELD);
    String title = getFormFieldContent(items, Constants.TITLE_FIELD);
    String description = getFormFieldContent(items, Constants.DESC_FIELD);
    String contentType = getFormFieldContent(items, Constants.TYPE_FIELD);

    FileItem fileField = getFileFormField(items);

    if (fileField == null) {
        throw new FileUploadException("Must provide the file data.");
    }

    byte[] dataArray = fileField.get();

    if (contentType == null) {
        if (fileField.getContentType() != null) {
            contentType = fileField.getContentType();
        } else {
            throw new FileUploadException("Must provide a " + Constants.TYPE_FIELD + " for the uploaded file.");
        }
    }

    // storing
    Media media = storeMedia(fileName, title, description, XMPPUtils.getBareId(userId), entityId, contentType,
            dataArray, isAvatar);

    LOGGER.debug("Media sucessfully added. Media ID: " + media.getId());

    return gson.toJson(media);
}

From source file:com.servlet.tools.FileUploadHelper.java

public boolean Initialize() {
    boolean result;
    String tempRealPath;//w  w  w  . j av a 2 s .com
    File repository;
    int sizeThreshold;
    DiskFileItemFactory diskFileItemFactory;
    ServletFileUpload fileUpload;
    try {
        tempRealPath = SystemInfo.ProjectRealPath + File.separator + tempFilePath;
        if (!FileHelper.CheckAndCreateDirectory(tempRealPath)) {
            //                log
            return false;
        }
        this.relativePath = MappingRelativePath();
        System.out.println(tempRealPath);
        repository = new File(tempRealPath);
        sizeThreshold = 1024 * 6;
        diskFileItemFactory = new DiskFileItemFactory();
        diskFileItemFactory.setRepository(repository);
        diskFileItemFactory.setSizeThreshold(sizeThreshold);
        fileUpload = new ServletFileUpload(diskFileItemFactory);
        fileUpload.setSizeMax(limitedSize);
        fileUpload.setHeaderEncoding("UTF-8");
        result = true;
    } catch (Exception ex) {
        fileUpload = null;
        result = false;
        //log
    }
    if (result) {
        this.servletFileUpload = fileUpload;
    }
    return result;
}