Example usage for org.apache.commons.fileupload FileItem getSize

List of usage examples for org.apache.commons.fileupload FileItem getSize

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem getSize.

Prototype

long getSize();

Source Link

Document

Returns the size of the file item.

Usage

From source file:org.mentawai.util.DebugServletFilter.java

private static void printOutput(StringBuffer sb, Output output) {

    if (sb == null)
        return;//from   ww  w.ja  v  a  2  s .  c o m

    clearHtmlTags(COMMENTED);

    Iterator<String> iter = output.keys();
    boolean isEmpty = true;

    while (iter.hasNext()) {

        String name = iter.next();

        if (name.equals(DebugServletFilter.DEBUG_KEY))
            continue;

        Object value = output.getValue(name);

        String s = null;
        if (value instanceof Collection) {
            int size = ((Collection) value).size();
            s = value != null ? " Collection of " + size + " elements: " + value.toString() : "null";
        } else if (value != null
                && value.getClass().getName().equals("org.apache.commons.fileupload.FileItem")) {

            FileItem fi = (FileItem) value;

            String filename = fi.getName();

            if (filename != null && !filename.trim().equals("")) {

                s = "File Upload: " + filename + " (" + fi.getSize() + " bytes)";

            } else {

                s = "";
            }

        } else {
            s = value != null ? value.toString() : "null";
        }

        if (s.length() > 100)
            s = s.substring(0, 100) + " ...";

        s = s.replace('\n', ' ');

        sb.append('\t').append(name).append(" = ").append(s).append("\n");

        isEmpty = false;
    }

    if (isEmpty)
        sb.append("\t" + htmlOpenItalic + "empty" + htmlCloseItalic + "\n");
}

From source file:org.mhi.imageutilities.FileHandler.java

public InputStream getFile(String file_field) throws IOException {
    InputStream blob = null;// w ww  .  ja  v  a2  s.c o m
    Iterator<FileItem> iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = iter.next();
        if (item.getFieldName().equals(file_field)) {
            blob = item.getInputStream();
            setContentType(item.getContentType());
            setFileSize(item.getSize());
            setFileName(item.getName());

        }
    }
    return blob;
}

From source file:org.mikha.utils.web.examples.FormsServlet.java

/**
 * Parses "file" form./*  w w  w.  j  a v  a 2s  .c  o  m*/
 * @param req request
 * @param rsp response
 * @throws ServletException if failed to forward
 * @throws IOException if failed to forward
 */
@ControllerMethodMapping(paths = "/file")
public String parseFileForm(HttpParamsRequest req, HttpServletResponse rsp)
        throws ServletException, IOException {
    String submit = req.getParameter("submit");

    if (submit != null) {
        FileItem file = req.getFile("file");
        if (!req.hasRecentErrors()) {
            rsp.setContentType(file.getContentType());
            rsp.setContentLength((int) file.getSize());
            rsp.getOutputStream().write(file.get());
            return null;
        }
    }

    return "fileform.jsp";
}

From source file:org.mikha.utils.web.examples.MultipartServlet.java

protected void doPost(HttpParamsRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    FileItem file = request.getFile("myfile");
    if (file == null) {
        throw new ServletException("File \"myfile\" is not found in uploaded data");
    }//ww  w.  ja  va  2  s. c om

    response.setContentType(file.getContentType());
    response.setContentLength((int) file.getSize());
    response.getOutputStream().write(file.get());
}

From source file:org.mitre.medj.WebUtils.java

public static List<ContinuityOfCareRecord> translateFiles(List<FileItem> items, String pathName) {

    try {// w  ww  .ja v a  2  s  . co  m
        ArrayList<ContinuityOfCareRecord> ccrs = new ArrayList<ContinuityOfCareRecord>();
        System.out.println("WebUtils uploadFile : got items " + items);
        boolean writeToFile = true;
        System.out.println("WebUtils uploadFile : got items " + items.size());

        for (FileItem fileSetItem : items) {
            String itemName = fileSetItem.getFieldName();
            System.out.println("WebUtils: first file item  " + itemName);

            String fileName = "";
            if (!fileSetItem.isFormField()) {
                String fieldName = fileSetItem.getFieldName();
                fileName = fileSetItem.getName();

                String contentType = fileSetItem.getContentType();
                boolean isInMemory = fileSetItem.isInMemory();
                long sizeInBytes = fileSetItem.getSize();

                ContinuityOfCareRecord ccr = translate(fileSetItem.getString());
                String patientId = getPatientId(ccr);

                uploadFile(fileSetItem, pathName, fileName, patientId);
                if (ccr != null)
                    ccrs.add(ccr);

            }

        }
        return ccrs;

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
}

From source file:org.mojavemvc.core.HttpParameterMapSource.java

private void processUploadedFile(FileItem item, Map<String, Object> paramMap) throws IOException {

    String fieldName = item.getFieldName();
    String fileName = item.getName();
    String contentType = item.getContentType();
    boolean isInMemory = item.isInMemory();
    long sizeInBytes = item.getSize();
    InputStream uploadedStream = item.getInputStream();

    paramMap.put(fieldName, new UploadedFile(fileName, uploadedStream, contentType, isInMemory, sizeInBytes));
}

From source file:org.mskcc.cbio.portal.servlet.EchoFile.java

/**
 *
 * If you specify the `str` parameter in the request, the servlet echoes back the string as is.
 *
 * If you specify files in the request, each file gets echoed back as a json object
 * { name -> string (content of file)}
 *
 * @param request//  www.  ja va2s . c om
 * @param response
 * @throws ServletException
 * @throws IOException
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Writer writer = response.getWriter();

    try {

        String str = request.getParameter("str");

        if (str != null) {
            writer.write(request.getParameter("str"));
            return;
        }

        Map fieldName2fileContent = new HashMap<String, String>();

        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

        for (FileItem item : items) {
            if (item.getSize() == 0) {
                // skip empty files
                continue;
            }

            InputStream contentStream = item.getInputStream();
            String fieldName = item.getFieldName();

            // slurp the file as a string
            String encoding = "UTF-8";
            StringWriter stringWriter = new StringWriter();
            IOUtils.copy(contentStream, stringWriter, encoding);
            String contentString = stringWriter.toString();

            fieldName2fileContent.put(fieldName, contentString);
        }

        // write the objects out as json
        response.setContentType("application/json");
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(writer, fieldName2fileContent);
    }

    // catch all exceptions
    catch (Exception e) {

        // "log" it
        System.out.println(e);

        // hide details from user
        throw new ServletException("there was an error processing your request");
    }
}

From source file:org.muse.mneme.impl.AttachmentServiceImpl.java

/**
 * {@inheritDoc}/*from w  w  w.ja va  2 s . co  m*/
 */
public Reference addAttachment(String application, String context, String prefix, boolean uniqueHolder,
        FileItem file) {
    pushAdvisor();

    try {
        String name = file.getName();
        if (name != null) {
            name = massageName(name);
        }

        String type = file.getContentType();

        // TODO: change to file.getInputStream() for after Sakai 2.3 more efficient support
        // InputStream body = file.getInputStream();
        byte[] body = file.get();

        long size = file.getSize();

        // detect no file selected
        if ((name == null) || (type == null) || (body == null) || (size == 0)) {
            // TODO: if using input stream, close it
            // if (body != null) body.close();
            return null;
        }

        Reference rv = doAdd(contentHostingId(name, application, context, prefix, uniqueHolder), name, type,
                body, size, false);

        // if this failed, and we are not using a uniqueHolder, try it with a uniqueHolder
        if ((rv == null) && !uniqueHolder) {
            rv = doAdd(contentHostingId(name, application, context, prefix, true), name, type, body, size,
                    false);
        }

        // TODO: we might not want a thumb (such as for submission uploads to essay/task
        // if we added one
        if (rv != null) {
            // if it is an image
            if (type.toLowerCase().startsWith("image/")) {
                addThumb(rv, name, body);
            }
        }

        return rv;
    } finally {
        popAdvisor();
    }
}

From source file:org.mycore.frontend.editor.MCREditorServlet.java

private void sendToDebug(HttpServletResponse res, Document unprocessed, MCREditorSubmission sub)
        throws IOException, UnsupportedEncodingException {
    res.setContentType("text/html; charset=UTF-8");

    PrintWriter pw = res.getWriter();

    pw.println("<html><body><p><pre>");

    for (int i = 0; i < sub.getVariables().size(); i++) {
        MCREditorVariable var = (MCREditorVariable) sub.getVariables().get(i);
        pw.println(var.getPath() + " = " + var.getValue());

        FileItem file = var.getFile();

        if (file != null) {
            pw.println("      is uploaded file " + file.getContentType() + ", " + file.getSize() + " bytes");
        }/*from   www .  j  a  va 2s.  c  o  m*/
    }

    pw.println("</pre></p><p>");

    XMLOutputter outputter = new XMLOutputter();
    Format fmt = Format.getPrettyFormat();
    fmt.setLineSeparator("\n");
    fmt.setOmitDeclaration(true);
    outputter.setFormat(fmt);

    Element pre = new Element("pre");
    pre.addContent(outputter.outputString(unprocessed));
    outputter.output(pre, pw);

    pre = new Element("pre");
    pre.addContent(outputter.outputString(sub.getXML()));
    outputter.output(pre, pw);

    pw.println("</p></body></html>");
    pw.close();
}

From source file:org.mycore.frontend.fileupload.MCRUploadViaFormServlet.java

private void handleUploadedFile(MCRUploadHandler handler, FileItem file) throws IOException, Exception {
    InputStream in = file.getInputStream();
    String path = MCRUploadHelper.getFileName(file.getName());

    MCRConfiguration config = MCRConfiguration.instance();
    if (config.getBoolean("MCR.FileUpload.DecompressZip", true)
            && path.toLowerCase(Locale.ROOT).endsWith(".zip"))
        handleZipFile(handler, in);//from  w ww.  ja  v a  2  s  .c  om
    else
        handleUploadedFile(handler, file.getSize(), path, in);
}