Example usage for org.apache.commons.fileupload FileUpload FileUpload

List of usage examples for org.apache.commons.fileupload FileUpload FileUpload

Introduction

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

Prototype

public FileUpload(FileItemFactory fileItemFactory) 

Source Link

Document

Constructs an instance of this class which uses the supplied factory to create FileItem instances.

Usage

From source file:helma.servlet.AbstractServletClient.java

protected List parseUploads(ServletRequestContext reqcx, RequestTrans reqtrans, final UploadStatus uploadStatus,
        String encoding) throws FileUploadException, UnsupportedEncodingException {
    // handle file upload
    DiskFileItemFactory factory = new DiskFileItemFactory();
    FileUpload upload = new FileUpload(factory);
    // use upload limit for individual file size, but also set a limit on overall size
    upload.setFileSizeMax(uploadLimit * 1024);
    upload.setSizeMax(totalUploadLimit * 1024);

    // register upload tracker with user's session
    if (uploadStatus != null) {
        upload.setProgressListener(new ProgressListener() {
            public void update(long bytesRead, long contentLength, int itemsRead) {
                uploadStatus.update(bytesRead, contentLength, itemsRead);
            }/*ww w . j  a v a2s.co  m*/
        });
    }

    List uploads = upload.parseRequest(reqcx);
    Iterator it = uploads.iterator();

    while (it.hasNext()) {
        FileItem item = (FileItem) it.next();
        String name = item.getFieldName();
        Object value;
        // check if this is an ordinary HTML form element or a file upload
        if (item.isFormField()) {
            value = item.getString(encoding);
        } else {
            value = new MimePart(item);
        }
        // if multiple values exist for this name, append to _array
        reqtrans.addPostParam(name, value);
    }
    return uploads;
}

From source file:axiom.servlet.AbstractServletClient.java

protected List parseUploads(ServletRequestContext reqcx, RequestTrans reqtrans, final UploadStatus uploadStatus,
        String encoding) throws FileUploadException, UnsupportedEncodingException {

    List uploads = null;// w w w .j  a  v  a2s .  com
    Context cx = Context.enter();
    ImporterTopLevel scope = new ImporterTopLevel(cx, true);

    try {
        // handle file upload
        DiskFileItemFactory factory = new DiskFileItemFactory();
        FileUpload upload = new FileUpload(factory);
        // use upload limit for individual file size, but also set a limit on overall size
        upload.setFileSizeMax(uploadLimit * 1024);
        upload.setSizeMax(totalUploadLimit * 1024);

        // register upload tracker with user's session
        if (uploadStatus != null) {
            upload.setProgressListener(new ProgressListener() {
                public void update(long bytesRead, long contentLength, int itemsRead) {
                    uploadStatus.update(bytesRead, contentLength, itemsRead);
                }
            });
        }

        uploads = upload.parseRequest(reqcx);
        Iterator it = uploads.iterator();

        while (it.hasNext()) {
            FileItem item = (FileItem) it.next();
            String name = item.getFieldName();
            Object value = null;
            // check if this is an ordinary HTML form element or a file upload
            if (item.isFormField()) {
                value = item.getString(encoding);
            } else {
                String itemName = item.getName().trim();
                if (itemName == null || itemName.equals("")) {
                    continue;
                }
                value = new MimePart(itemName, item.get(), item.getContentType());
                value = new NativeJavaObject(scope, value, value.getClass());
            }
            item.delete();
            // if multiple values exist for this name, append to _array

            // reqtrans.addPostParam(name, value); ????

            Object ret = reqtrans.get(name);
            if (ret != null && ret != Scriptable.NOT_FOUND) {
                appendFormValue(reqtrans, name, value);
            } else {
                reqtrans.set(name, value);
            }
        }
    } finally {
        Context.exit();
    }

    return uploads;
}

From source file:com.slamd.admin.AdminServlet.java

/**
 * Handles the work of actually accepting an uploaded file and storing it in
 * the configuration directory.//from   w w  w  .  ja va 2 s .com
 *
 * @param  requestInfo  The state information for this request.
 */
static void handleFileUpload(RequestInfo requestInfo) {
    logMessage(requestInfo, "In handleFileUpload()");

    if (!requestInfo.mayManageFolders) {
        logMessage(requestInfo, "No mayManageFolders permission granted");
        generateAccessDeniedBody(requestInfo,
                "You do not have permission to " + "upload files into job folders.");
        return;
    }

    StringBuilder infoMessage = requestInfo.infoMessage;

    FileUpload fileUpload = new FileUpload(new DefaultFileItemFactory());
    fileUpload.setSizeMax(maxUploadSize);

    boolean inOptimizing = false;
    String folderName = null;

    try {
        String fileName = null;
        String fileType = null;
        String fileDesc = null;
        int fileSize = -1;
        byte[] fileData = null;

        Iterator iterator = requestInfo.multipartFieldList.iterator();
        while (iterator.hasNext()) {
            FileItem fileItem = (FileItem) iterator.next();
            String fieldName = fileItem.getFieldName();

            if (fieldName.equals(Constants.SERVLET_PARAM_FILE_DESCRIPTION)) {
                fileDesc = new String(fileItem.get());
            } else if (fieldName.equals(Constants.SERVLET_PARAM_JOB_FOLDER)) {
                folderName = new String(fileItem.get());
            } else if (fieldName.equals(Constants.SERVLET_PARAM_UPLOAD_FILE)) {
                fileData = fileItem.get();
                fileSize = fileData.length;
                fileType = fileItem.getContentType();
                fileName = fileItem.getName();
            } else if (fieldName.equals(Constants.SERVLET_PARAM_IN_OPTIMIZING)) {
                String optStr = new String(fileItem.get());
                inOptimizing = optStr.equalsIgnoreCase("true");
            }
        }

        if (fileName == null) {
            infoMessage.append(
                    "Unable to process file upload:  did not receive " + "any actual file data.<BR>" + EOL);
            if (inOptimizing) {
                handleViewOptimizing(requestInfo, true, folderName);
            } else {
                handleViewJob(requestInfo, Constants.SERVLET_SECTION_JOB_VIEW_COMPLETED, folderName, null);
            }
            return;
        }

        UploadedFile file = new UploadedFile(fileName, fileType, fileSize, fileDesc, fileData);
        configDB.writeUploadedFile(file, folderName);
        infoMessage.append("Successfully uploaded file \"" + fileName + "\"<BR>" + EOL);
    } catch (Exception e) {
        infoMessage.append("Unable to process file upload:  " + e + "<BR>" + EOL);
    }

    if (inOptimizing) {
        handleViewOptimizing(requestInfo, true, folderName);
    } else {
        handleViewJob(requestInfo, Constants.SERVLET_SECTION_JOB_VIEW_COMPLETED, folderName, null);
    }
}

From source file:org.etk.core.rest.impl.provider.MultipartFormDataEntityProvider.java

/**
 * {@inheritDoc}//from ww  w  .  j  a  v  a2  s .c  o  m
 */
@SuppressWarnings("unchecked")
public Iterator<FileItem> readFrom(Class<Iterator<FileItem>> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
        throws IOException {
    try {
        ApplicationContext context = ApplicationContextImpl.getCurrent();
        int bufferSize = (Integer) context.getAttributes().get(RequestHandler.WS_RS_BUFFER_SIZE);
        File repo = (File) context.getAttributes().get(RequestHandler.WS_RS_TMP_DIR);

        DefaultFileItemFactory factory = new DefaultFileItemFactory(bufferSize, repo);
        FileUpload upload = new FileUpload(factory);
        return upload.parseRequest(httpRequest).iterator();
    } catch (FileUploadException e) {
        throw new IOException("Can't process multipart data item " + e);
    }
}

From source file:org.everrest.core.impl.provider.ext.InMemoryMultipartFormDataEntityProvider.java

@SuppressWarnings("unchecked")
@Override/*from  ww w . j  a va 2s  . co m*/
public Iterator<FileItem> readFrom(Class<Iterator<FileItem>> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
        throws IOException {
    try {
        ApplicationContext context = ApplicationContextImpl.getCurrent();
        int bufferSize = context.getEverrestConfiguration().getMaxBufferSize();
        FileItemFactory factory = new InMemoryItemFactory(bufferSize);
        FileUpload upload = new FileUpload(factory);
        return upload.parseRequest(httpRequest).iterator();
    } catch (FileUploadException e) {
        throw new IOException("Can't process multipart data item " + e);
    }
}

From source file:org.everrest.core.impl.provider.MultipartFormDataEntityProvider.java

@Override
@SuppressWarnings("unchecked")
public Iterator<FileItem> readFrom(Class<Iterator<FileItem>> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
        throws IOException {
    try {//from ww  w  . j a va  2s.c o m
        ApplicationContext context = ApplicationContextImpl.getCurrent();
        int bufferSize = context.getEverrestConfiguration().getMaxBufferSize();
        DefaultFileItemFactory factory = new DefaultFileItemFactory(bufferSize,
                FileCollector.getInstance().getStore());
        FileUpload upload = new FileUpload(factory);
        return upload.parseRequest(httpRequest).iterator();
    } catch (FileUploadException e) {
        throw new IOException("Can't process multipart data item " + e);
    }
}

From source file:org.exoplatform.services.rest.impl.provider.MultipartFormDataEntityProvider.java

/**
 * {@inheritDoc}//from w w w  . jav  a  2 s  .  c  o m
 */
@SuppressWarnings("unchecked")
public Iterator<FileItem> readFrom(Class<Iterator<FileItem>> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
        throws IOException {
    try {
        ApplicationContext context = ApplicationContextImpl.getCurrent();
        int bufferSize = context.getProperties().get(RequestHandler.WS_RS_BUFFER_SIZE) == null
                ? RequestHandler.WS_RS_BUFFER_SIZE_VALUE
                : Integer.parseInt(context.getProperties().get(RequestHandler.WS_RS_BUFFER_SIZE));
        File repo = new File(context.getProperties().get(RequestHandler.WS_RS_TMP_DIR));

        DefaultFileItemFactory factory = new DefaultFileItemFactory(bufferSize, repo);
        final FileUpload upload = new FileUpload(factory);

        return SecurityHelper.doPrivilegedExceptionAction(new PrivilegedExceptionAction<Iterator<FileItem>>() {
            public Iterator<FileItem> run() throws Exception {
                return upload.parseRequest(httpRequest).iterator();
            }
        });
    } catch (PrivilegedActionException pae) {
        Throwable cause = pae.getCause();
        if (cause instanceof FileUploadException) {
            throw new IOException("Can't process multipart data item " + cause, cause);
        } else if (cause instanceof RuntimeException) {
            throw (RuntimeException) cause;
        } else {
            throw new RuntimeException(cause);
        }
    }
}

From source file:org.nuxeo.ecm.platform.ui.web.util.FileUploadHelper.java

/**
 * Parses a Multipart Servlet Request to extract blobs
 *///from   ww w  . j a va  2 s . co m
public static List<Blob> parseRequest(HttpServletRequest request) throws FileUploadException, IOException {
    List<Blob> blobs = new ArrayList<Blob>();

    if (request instanceof MultipartRequest) {
        MultipartRequest seamMPRequest = (MultipartRequest) request;

        Enumeration<String> names = seamMPRequest.getParameterNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            try (InputStream in = seamMPRequest.getFileInputStream(name)) {
                if (in != null) {
                    Blob blob = Blobs.createBlob(in);
                    blob.setFilename(seamMPRequest.getFileName(name));
                    blobs.add(blob);
                }
            }
        }
    } else {
        // fallback method for non-seam servlet request
        FileUpload fu = new FileUpload(new DiskFileItemFactory());
        String fileNameCharset = request.getHeader("FileNameCharset");
        if (fileNameCharset != null) {
            fu.setHeaderEncoding(fileNameCharset);
        }
        ServletRequestContext requestContext = new ServletRequestContext(request);
        List<FileItem> fileItems = fu.parseRequest(requestContext);
        for (FileItem item : fileItems) {
            try (InputStream is = item.getInputStream()) {
                Blob blob = Blobs.createBlob(is);
                blob.setFilename(item.getName());
                blobs.add(blob);
            }
        }
    }
    return blobs;
}

From source file:org.oscarehr.olis.OLISUploadSimulationDataAction.java

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {/*w  w w.  j  a v a2  s. c  om*/

    Logger logger = MiscUtils.getLogger();

    String simulationData = null;
    boolean simulationError = false;

    try {
        FileUpload upload = new FileUpload(new DefaultFileItemFactory());
        @SuppressWarnings("unchecked")
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()) {
                String name = item.getFieldName();
                if (name.equals("simulateError")) {
                    simulationError = true;
                }
            } else {
                if (item.getFieldName().equals("simulateFile")) {
                    InputStream is = item.getInputStream();
                    StringWriter writer = new StringWriter();
                    IOUtils.copy(is, writer, "UTF-8");
                    simulationData = writer.toString();
                }
            }
        }

        if (simulationData != null && simulationData.length() > 0) {
            if (simulationError) {
                Driver.readResponseFromXML(request, simulationData);
                simulationData = (String) request.getAttribute("olisResponseContent");
                request.getSession().setAttribute("errors", request.getAttribute("errors"));
            }
            request.getSession().setAttribute("olisResponseContent", simulationData);
            request.setAttribute("result", "File successfully uploaded");
        }
    } catch (Exception e) {
        MiscUtils.getLogger().error("Error", e);
    }

    return mapping.findForward("success");
}

From source file:org.springframework.http.converter.FormHttpMessageConverterTests.java

@Test
public void writeMultipart() throws Exception {
    MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
    parts.add("name 1", "value 1");
    parts.add("name 2", "value 2+1");
    parts.add("name 2", "value 2+2");
    parts.add("name 3", null);

    Resource logo = new ClassPathResource("/org/springframework/http/converter/logo.jpg");
    parts.add("logo", logo);

    // SPR-12108/*from  w  w  w.j  a  v  a  2s.  co  m*/
    Resource utf8 = new ClassPathResource("/org/springframework/http/converter/logo.jpg") {
        @Override
        public String getFilename() {
            return "Hall\u00F6le.jpg";
        }
    };
    parts.add("utf8", utf8);

    Source xml = new StreamSource(new StringReader("<root><child/></root>"));
    HttpHeaders entityHeaders = new HttpHeaders();
    entityHeaders.setContentType(MediaType.TEXT_XML);
    HttpEntity<Source> entity = new HttpEntity<>(xml, entityHeaders);
    parts.add("xml", entity);

    MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
    this.converter.write(parts, new MediaType("multipart", "form-data", StandardCharsets.UTF_8), outputMessage);

    final MediaType contentType = outputMessage.getHeaders().getContentType();
    assertNotNull("No boundary found", contentType.getParameter("boundary"));

    // see if Commons FileUpload can read what we wrote
    FileItemFactory fileItemFactory = new DiskFileItemFactory();
    FileUpload fileUpload = new FileUpload(fileItemFactory);
    RequestContext requestContext = new MockHttpOutputMessageRequestContext(outputMessage);
    List<FileItem> items = fileUpload.parseRequest(requestContext);
    assertEquals(6, items.size());
    FileItem item = items.get(0);
    assertTrue(item.isFormField());
    assertEquals("name 1", item.getFieldName());
    assertEquals("value 1", item.getString());

    item = items.get(1);
    assertTrue(item.isFormField());
    assertEquals("name 2", item.getFieldName());
    assertEquals("value 2+1", item.getString());

    item = items.get(2);
    assertTrue(item.isFormField());
    assertEquals("name 2", item.getFieldName());
    assertEquals("value 2+2", item.getString());

    item = items.get(3);
    assertFalse(item.isFormField());
    assertEquals("logo", item.getFieldName());
    assertEquals("logo.jpg", item.getName());
    assertEquals("image/jpeg", item.getContentType());
    assertEquals(logo.getFile().length(), item.getSize());

    item = items.get(4);
    assertFalse(item.isFormField());
    assertEquals("utf8", item.getFieldName());
    assertEquals("Hall\u00F6le.jpg", item.getName());
    assertEquals("image/jpeg", item.getContentType());
    assertEquals(logo.getFile().length(), item.getSize());

    item = items.get(5);
    assertEquals("xml", item.getFieldName());
    assertEquals("text/xml", item.getContentType());
    verify(outputMessage.getBody(), never()).close();
}