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

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

Introduction

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

Prototype

String getContentType();

Source Link

Document

Returns the content type passed by the browser or null if not defined.

Usage

From source file:org.nema.medical.mint.server.controller.JobsController.java

public void handleUpload(HttpServletRequest request, File jobFolder, List<File> files,
        Map<String, String> params) throws IOException, FileUploadException {

    byte buf[] = new byte[32 * 1024];

    int fileCount = 0;
    LOG.info("creating local files");

    // Parse the request
    ServletFileUpload upload = new ServletFileUpload();
    FileItemIterator iter;// www.jav  a  2s  . c  om
    iter = upload.getItemIterator(request);
    while (iter.hasNext()) {
        FileItemStream item = iter.next();
        String name = item.getFieldName();
        InputStream in = item.openStream();

        if (item.isFormField()) {
            String value = Streams.asString(in);
            LOG.debug("found form field " + name + " = " + value);
            params.put(name, value);
        } else {
            File file;

            // special handling for first file - must be metadata!
            if (files.isEmpty()) {
                String filename = item.getName();

                LOG.info("loading metadata from " + filename);
                outer: {
                    for (String extension : supportedMetadataExtensions) {
                        if (filename.endsWith(extension)) {
                            filename = "metadata" + extension;
                            break outer;
                        }
                    }

                    //At this point, no proper filename has been established. Last resort, use content type!
                    String contentType = item.getContentType();
                    if ("text/xml".equals(contentType)) {
                        filename = "metadata.xml";
                    } else if ("application/octet-stream".equals(contentType)) {
                        filename = "metadata.gpb";
                    } else {
                        // dump out and write the content... will fail later
                        LOG.error("unable to determine metadata type for " + item.getName());
                        filename = "metadata.dat";
                    }
                }

                file = new File(jobFolder, filename);
            } else {
                final String msgPartName = item.getFieldName();
                try {
                    if (!msgPartName.startsWith("binary")) {
                        throw new Exception();
                    }
                    final String itemIdStr = msgPartName.substring("binary".length());
                    final int itemId = Integer.parseInt(itemIdStr);
                    file = new File(jobFolder, String.format("%d.dat", itemId));
                } catch (final Exception e) {
                    throw new IOException("Invalid message part name for binary data: '" + msgPartName
                            + "'; must start with 'binary', followed by a number");
                }
            }

            if (file.exists()) {
                throw new IOException("File for message part already exists: '" + file.getName() + "'");
            }
            FileOutputStream out = null;
            out = new FileOutputStream(file);
            try {
                while (true) {
                    int len = in.read(buf);
                    if (len < 0)
                        break;
                    out.write(buf, 0, len);
                }
            } finally {
                if (out != null) {
                    out.close();
                    files.add(file);
                    fileCount++;
                }
            }
        }
    }
    LOG.info("created " + fileCount + " files.");
}

From source file:org.odk.aggregate.parser.MultiPartFormData.java

/**
 * Construct a mult-part form data container by parsing
 * a multi part form request into a set of multipartformitems. The
 * information are stored in items and are indexed by either 
 * the field name or the file name (or both) provided in the http submission
 * //  www  .j  av  a  2 s  .  com
 * @param req
 *     an HTTP request from a multipart form 
        
 * @throws FileUploadException
 * @throws IOException
 */
public MultiPartFormData(HttpServletRequest req) throws FileUploadException, IOException {

    fieldNameMap = new HashMap<String, MultiPartFormItem>();
    fileNameMap = new HashMap<String, MultiPartFormItem>();

    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    upload.setFileSizeMax(ParserConsts.FILE_SIZE_MAX);

    FileItemIterator items = upload.getItemIterator(req);
    while (items.hasNext()) {
        FileItemStream item = items.next();
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        BufferedInputStream formStream = new BufferedInputStream(item.openStream());

        // TODO: determine ways to possibly improve efficiency
        int nextByte = formStream.read();
        while (nextByte != -1) {
            byteStream.write(nextByte);
            nextByte = formStream.read();
        }

        MultiPartFormItem data = new MultiPartFormItem(item.getFieldName(), item.getName(),
                item.getContentType(), byteStream);

        String fieldName = item.getFieldName();
        if (fieldName != null) {
            fieldNameMap.put(fieldName, data);
        }

        String fileName = item.getName();
        if (fileName != null) {
            // TODO: possible bug in ODK collect is truncating file extension
            // may need to remove this code after ODK collect is fixed
            int indexOfExtension = fileName.lastIndexOf(".");
            if (indexOfExtension > 0) {
                fileNameMap.put(fileName.substring(0, indexOfExtension), data);
            }
            fileNameMap.put(fileName, data);
        }
        formStream.close();
    }
}

From source file:org.odk.voice.storage.MultiPartFormData.java

/**
 * Construct a mult-part form data container by parsing
 * a multi part form request into a set of multipartformitems. The
 * information are stored in items and are indexed by either 
 * the field name or the file name (or both) provided in the http submission
 * /*from   www  . j  av a  2  s.c o m*/
 * @param req
 *     an HTTP request from a multipart form 
        
 * @throws FileUploadException
 * @throws IOException
 */
public MultiPartFormData(HttpServletRequest req) throws FileUploadException, IOException {

    fieldNameMap = new HashMap<String, MultiPartFormItem>();
    fileNameMap = new HashMap<String, MultiPartFormItem>();

    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    upload.setFileSizeMax(FileConstants.MAX_FILE_SIZE);

    FileItemIterator items = upload.getItemIterator(req);
    while (items.hasNext()) {
        FileItemStream item = items.next();
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        BufferedInputStream formStream = new BufferedInputStream(item.openStream());

        // TODO: determine ways to possibly improve efficiency
        int nextByte = formStream.read();
        while (nextByte != -1) {
            byteStream.write(nextByte);
            nextByte = formStream.read();
        }

        MultiPartFormItem data = new MultiPartFormItem(item.getFieldName(), item.getName(),
                item.getContentType(), byteStream.toByteArray());

        String fieldName = item.getFieldName();
        if (fieldName != null) {
            fieldNameMap.put(fieldName, data);
        }

        String fileName = item.getName();
        if (fileName != null) {
            // TODO: possible bug in ODK collect is truncating file extension
            // may need to remove this code after ODK collect is fixed
            int indexOfExtension = fileName.lastIndexOf(".");
            if (indexOfExtension > 0) {
                fileNameMap.put(fileName.substring(0, indexOfExtension), data);
            }
            fileNameMap.put(fileName, data);
        }
    }
}

From source file:org.olat.core.gui.components.form.flexible.impl.Form.java

/**
 * Internal helper to initialize the request parameter map an to temporary store the uploaded files when a multipart request is used. The files are stored to a
 * temporary location and a filehandle is added to the requestMultipartFiles map for later retrieval by the responsible FormItem.
 * //w w w  .  j a va  2 s. co m
 * @param ureq
 */
private void doInitRequestParameterAndMulipartData(UserRequest ureq) {
    // First fill parameter map either from multipart data or standard http request
    if (isMultipartEnabled() && ServletFileUpload.isMultipartContent(ureq.getHttpReq())) {
        long uploadSize = -1; // default unlimited
        // Limit size of complete upload form: upload size limit + 500k for
        // other input fields
        if (multipartUploadMaxSizeKB > -1) {
            uploadSize = (multipartUploadMaxSizeKB * 1024l * 1024l) + 512000l;
        }

        // Create a new file upload handler, use commons fileupload streaming
        // API to save files right to the tmp location
        ServletFileUpload uploadParser = new ServletFileUpload();
        uploadParser.setSizeMax(uploadSize);
        // Parse the request
        try {
            FileItemIterator iter = uploadParser.getItemIterator(ureq.getHttpReq());
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                String itemName = item.getFieldName();
                InputStream itemStream = item.openStream();
                if (item.isFormField()) {
                    // Normal form item
                    // analog to ureq.getParameter in non-multipart mode
                    String value = Streams.asString(itemStream, "UTF-8");
                    addRequestParameter(itemName, value);
                } else {
                    // File item, store it to temp location
                    String fileName = item.getName();
                    // Cleanup IE filenames that are absolute
                    int slashpos = fileName.lastIndexOf("/");
                    if (slashpos != -1)
                        fileName = fileName.substring(slashpos + 1);
                    slashpos = fileName.lastIndexOf("\\");
                    if (slashpos != -1)
                        fileName = fileName.substring(slashpos + 1);

                    File tmpFile = new File(System.getProperty("java.io.tmpdir") + File.separator + "upload-"
                            + CodeHelper.getGlobalForeverUniqueID());

                    try {
                        FileUtils.save(itemStream, tmpFile);
                        // Only save non-empty file transfers, ignore empty transfers
                        // (e.g. already submitted in a previous form submit, not an error!)

                        // Removing empty file check for now ... was introduced to cope with
                        // browser trouble which probably is not there any more ...
                        // so empty fileName means nothing selected in the file element

                        // if (tmpFile.length() > 0) {
                        if (fileName.length() > 0) {
                            // a file was selected
                            // Save file and also original file name
                            requestMultipartFiles.put(itemName, tmpFile);
                            requestMultipartFileNames.put(itemName, fileName);
                            requestMultipartFileMimeTypes.put(itemName, item.getContentType());
                        } else {
                            if (tmpFile.exists())
                                tmpFile.delete();
                        }
                    } catch (OLATRuntimeException e) {
                        // Could not save stream for whatever reason, cleanup temp file and delegate exception
                        if (tmpFile.exists())
                            tmpFile.delete();

                        if (e.getCause() instanceof MalformedStreamException) {
                            logWarn("Could not read uploaded file >" + fileName
                                    + "< from stream. Possibly an attempt to upload a directory instead of a file (happens on Mac)",
                                    e);
                            return;
                        }

                        throw new OLATRuntimeException("Could not save uploaded file", e);
                    }
                }
            }
        } catch (SizeLimitExceededException sizeLimitExceededException) {
            logError("Error while dispatching multipart form: file limit (" + uploadSize + ") exceeded",
                    sizeLimitExceededException);
            requestError = REQUEST_ERROR_UPLOAD_LIMIT_EXCEEDED;
        } catch (IOException e) {
            logWarn("Error while dispatching multipart form: ioexception", e);
            requestError = REQUEST_ERROR_GENERAL;
        } catch (Exception e) {
            logError("Error while dispatching multipart form: general exception", e);
            requestError = REQUEST_ERROR_GENERAL;
        }
    } else {
        // Get parameters the standard way
        logDebug("Dispatching non-multipart form", null);
        Set<String> keys = ureq.getParameterSet();
        for (String key : keys) {
            String[] values = ureq.getHttpReq().getParameterValues(key);
            if (values != null) {
                requestParams.put(key, values);
            } else {
                addRequestParameter(key, ureq.getParameter(key));
            }
        }
    }
}

From source file:org.olat.restapi.support.MultipartReader.java

private final void apache(HttpServletRequest request, long uploadLimit) {
    ServletFileUpload uploadParser = new ServletFileUpload();
    uploadParser.setSizeMax((uploadLimit * 1024l) + 512000l);
    // Parse the request
    try {/*from   w ww.java2s. c o  m*/
        FileItemIterator iter = uploadParser.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String itemName = item.getFieldName();
            InputStream itemStream = item.openStream();
            if (item.isFormField()) {
                String value = Streams.asString(itemStream, "UTF-8");
                fields.put(itemName, value);
            } else {
                // File item, store it to temp location
                filename = item.getName();
                contentType = item.getContentType();

                if (filename != null) {
                    filename = UUID.randomUUID().toString().replace("-", "") + "_" + filename;
                } else {
                    filename = "upload-" + UUID.randomUUID().toString().replace("-", "");
                }
                file = new File(WebappHelper.getTmpDir(), filename);
                try {
                    save(itemStream, file);
                } catch (Exception e) {
                    log.error("", e);
                }
            }
        }
    } catch (Exception e) {
        log.error("", e);
    }
}

From source file:org.opendatakit.aggregate.parser.MultiPartFormData.java

/**
 * Construct a mult-part form data container by parsing a multi part form
 * request into a set of multipartformitems. The information are stored in
 * items and are indexed by either the field name or the file name (or both)
 * provided in the http submission// w ww.  j  a  v a 2  s  .c o m
 * 
 * @param req
 *            an HTTP request from a multipart form
 * 
 * @throws FileUploadException
 * @throws IOException
 */
public MultiPartFormData(HttpServletRequest req) throws FileUploadException, IOException {

    simpleFieldNameMap = new HashMap<String, String>();
    fieldNameMap = new HashMap<String, MultiPartFormItem>();
    fileNameMap = new HashMap<String, MultiPartFormItem>();
    fileNameWithoutExtensionNameMap = new HashMap<String, MultiPartFormItem>();

    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    int size = req.getContentLength();
    if (size > 0) {
        upload.setFileSizeMax(size);
    } else {
        upload.setFileSizeMax(ParserConsts.FILE_SIZE_MAX);
    }

    List<MultiPartFormItem> fileNameList = new ArrayList<MultiPartFormItem>();

    FileItemIterator items = upload.getItemIterator(req);
    while (items.hasNext()) {
        FileItemStream item = items.next();
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        BufferedInputStream formStream = new BufferedInputStream(item.openStream());

        // TODO: determine ways to possibly improve efficiency
        int nextByte = formStream.read();
        while (nextByte != -1) {
            byteStream.write(nextByte);
            nextByte = formStream.read();
        }
        formStream.close();

        if (item.isFormField()) {
            simpleFieldNameMap.put(item.getFieldName(), byteStream.toString());
        } else {
            MultiPartFormItem data = new MultiPartFormItem(item.getFieldName(), item.getName(),
                    item.getContentType(), byteStream);

            String fieldName = item.getFieldName();
            if (fieldName != null) {
                fieldNameMap.put(fieldName, data);
            }
            String fileName = item.getName();
            if (fileName != null && fileName.length() != 0) {
                fileNameList.add(data);
            }
        }
    }

    // Find the common prefix to the filenames being uploaded...
    // Deal with Windows backslash file separator...
    boolean first = true;
    String[] commonPath = null;
    int commonPrefix = 0;
    for (MultiPartFormItem e : fileNameList) {
        String fullFilePath = e.getFilename();
        if (first) {
            commonPath = fullFilePath.split("[/\\\\]");
            commonPrefix = commonPath.length - 1; // everything but
            // filename...
            first = false;
        } else {
            String[] path = fullFilePath.split("[/\\\\]");
            int pathPrefix = path.length - 1; // everything but
            // filename...
            if (pathPrefix < commonPrefix)
                commonPrefix = pathPrefix;
            for (int i = 0; i < commonPrefix; ++i) {
                if (!commonPath[i].equals(path[i])) {
                    commonPrefix = i;
                    break;
                }
            }
        }
    }

    // and now go back through the attachments, adjusting the filename
    // and building the filename mapping.
    for (MultiPartFormItem e : fileNameList) {
        String fullFilePath = e.getFilename();
        String[] filePath = fullFilePath.split("[/\\\\]");
        StringBuilder b = new StringBuilder();
        first = true;
        // start at the first entry after the common prefix...
        for (int i = commonPrefix; i < filePath.length; ++i) {
            if (!first) {
                b.append("/");
            }
            first = false;
            b.append(filePath[i]);
        }
        // and construct the filename with common directory prefix
        // stripped.
        String fileName = b.toString();
        e.setFilename(fileName);
        if (fileName != null) {
            // TODO: possible bug in ODK collect truncating file extension
            // may need to remove this code after ODK collect is fixed
            int indexOfExtension = fileName.lastIndexOf(".");
            if (indexOfExtension > 0) {
                fileNameWithoutExtensionNameMap.put(fileName.substring(0, indexOfExtension), e);
            }
            fileNameMap.put(fileName, e);
        }
    }
}

From source file:org.openehealth.ipf.platform.camel.lbs.http.process.HttpResourceHandler.java

private void extractFromSinglePart(String subUnit, ResourceList resources, FileItemIterator iter)
        throws Exception {
    FileItemStream next = iter.next();
    InputStream inputStream = next.openStream();
    try {/*from  www. ja va 2  s. co m*/
        handleResource(subUnit, resources, next.getContentType(), next.getName(), next.getFieldName(),
                inputStream);
    } finally {
        inputStream.close();
    }
}

From source file:org.polymap.rap.updownload.upload.FileUploadServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {//from  w w  w . j  a v a2  s. c o m
        FileItemIterator it = fileUpload.getItemIterator(req);
        while (it.hasNext()) {
            FileItemStream item = it.next();
            String name = item.getFieldName();
            InputStream in = item.openStream();
            try {
                if (item.isFormField()) {
                    log.info("Form field " + name + " with value " + Streams.asString(in) + " detected.");
                } else {
                    log.info("File field " + name + " with file name " + item.getName() + " detected.");

                    String key = req.getParameter("handler");
                    assert key != null;
                    IUploadHandler handler = handlers.get(key);
                    // for the upload field we always get just one item (which has the length of the request!?)
                    int length = req.getContentLength();
                    handler.uploadStarted(item.getName(), item.getContentType(), length, in);
                }
            } finally {
                IOUtils.closeQuietly(in);
            }
        }
    } catch (Exception e) {
        log.warn("", e);
        throw new RuntimeException(e);
    }
}

From source file:org.polymap.rap.updownload.upload.UploadService.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    try {//from w  w w  .j av  a  2  s . c o m
        FileItemIterator it = fileUpload.getItemIterator(request);
        while (it.hasNext()) {
            FileItemStream item = it.next();

            try (InputStream in = item.openStream()) {
                if (item.isFormField()) {
                    log.info("Form field " + item.getFieldName() + " with value " + Streams.asString(in)
                            + " detected.");
                } else {
                    log.info("File field " + item.getFieldName() + " with file name " + item.getName()
                            + " detected.");

                    String handlerId = request.getParameter(ID_REQUEST_PARAM);
                    assert handlerId != null;
                    IUploadHandler handler = handlers.get(handlerId);
                    ClientFile clientFile = new ClientFile() {
                        @Override
                        public String getName() {
                            return item.getName();
                        }

                        @Override
                        public String getType() {
                            return item.getContentType();
                        }

                        @Override
                        public long getSize() {
                            // for the upload field we always get just one item (which has the length of the request!?)
                            return request.getContentLength();
                        }
                    };
                    handler.uploadStarted(clientFile, in);
                }
            }
        }
    } catch (Exception e) {
        log.warn("", e);
        throw new RuntimeException(e);
    }
}

From source file:org.restlet.example.ext.fileupload.FileUploadServerResource.java

@Post
public Representation accept(Representation entity) throws Exception {
    Representation result = null;/* w w  w  . j av a  2s  . c  o m*/
    if (entity != null && MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {
        // 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);

        // 3/ Request is parsed by the handler which generates a
        // list of FileItems
        FileItemIterator fileIterator = upload.getItemIterator(entity);

        // Process only the uploaded item called "fileToUpload"
        // and return back
        boolean found = false;
        while (fileIterator.hasNext() && !found) {
            FileItemStream fi = fileIterator.next();

            if (fi.getFieldName().equals("fileToUpload")) {
                // For the matter of sample code, it filters the multo
                // part form according to the field name.
                found = true;
                // consume the stream immediately, otherwise the stream
                // will be closed.
                StringBuilder sb = new StringBuilder("media type: ");
                sb.append(fi.getContentType()).append("\n");
                sb.append("file name : ");
                sb.append(fi.getName()).append("\n");
                BufferedReader br = new BufferedReader(new InputStreamReader(fi.openStream()));
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                sb.append("\n");
                result = new StringRepresentation(sb.toString(), MediaType.TEXT_PLAIN);
            }
        }
    } else {
        // POST request with no entity.
        setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
    }

    return result;
}