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

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

Introduction

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

Prototype

byte[] get();

Source Link

Document

Returns the contents of the file item as an array of bytes.

Usage

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

/**
 * {@inheritDoc}/*from   w  w w  . j  ava2 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.nuxeo.ecm.webengine.forms.FormData.java

protected Blob getBlob(FileItem item) {
    StreamSource src;//from  w  w  w .j  a  va 2  s  .co  m
    if (item.isInMemory()) {
        src = new ByteArraySource(item.get());
    } else {
        try {
            src = new InputStreamSource(item.getInputStream());
        } catch (IOException e) {
            throw WebException.wrap("Failed to get blob data", e);
        }
    }
    String ctype = item.getContentType();

    StreamingBlob blob = new StreamingBlob(src, ctype == null ? "application/octet-stream" : ctype);
    try {
        blob.persist();
    } catch (IOException e) {
        log.error(e, e);
    }
    blob.setFilename(item.getName());
    return blob;
}

From source file:org.nuxeo.ecm.webengine.util.FormData.java

protected Blob getBlob(FileItem item) throws WebException {
    StreamSource src;/* w  w  w . j  a  v a2 s  .  c  o m*/
    if (item.isInMemory()) {
        src = new ByteArraySource(item.get());
    } else {
        try {
            src = new InputStreamSource(item.getInputStream());
        } catch (IOException e) {
            throw new WebException("Failed to get blob data", e);
        }
    }
    String ctype = item.getContentType();
    StreamingBlob blob = new StreamingBlob(src, ctype == null ? "application/octet-stream" : ctype);
    blob.setFilename(item.getName());
    return blob;
}

From source file:org.nuxeo.opensocial.container.server.handler.AbstractActionHandler.java

protected static Blob getBlob(FileItem item) {
    StreamSource src;/*from   w  w w.j  a va  2s .  co  m*/
    if (item.isInMemory()) {
        src = new ByteArraySource(item.get());
    } else {
        try {
            src = new InputStreamSource(item.getInputStream());
        } catch (IOException e) {
            throw WebException.wrap("Failed to get blob data", e);
        }
    }
    String ctype = item.getContentType();
    StreamingBlob blob = new StreamingBlob(src, ctype == null ? "application/octet-stream" : ctype);
    blob.setFilename(item.getName());
    return blob;
}

From source file:org.nuxeo.theme.bank.Management.java

@POST
@Path("upload")
public Object uploadFile() {
    FormData form = ctx.getForm();/* w  ww  .java2s .  c  o  m*/

    String collection = form.getString("collection");
    String redirectUrl = form.getString("redirect_url");

    FileItem fileItem = form.getFileItem("file");
    if (!fileItem.isFormField()) {
        final byte[] fileData = fileItem.get();
        final String filename = fileItem.getName();
        final String path = String.format("%s/%s/image", bank, collection);
        try {
            BankManager.createFile(path, filename, fileData);
        } catch (IOException e) {
            throw new ThemeBankException(e.getMessage(), e);
        }
    }
    if (redirectUrl != null) {
        return redirect(redirectUrl);
    } else {
        return null;
    }
}

From source file:org.nuxeo.theme.webwidgets.Manager.java

public static String uploadFile(HttpServletRequest request, String providerName, String uid, String dataName)
        throws WidgetException, ProviderException {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<?> fileItems = null;
    try {//from  w ww. j a  v  a 2s. c  o m
        fileItems = upload.parseRequest(request);
    } catch (FileUploadException e) {
        log.error("Could not upload file", e);
    }
    if (fileItems == null) {
        log.error("No file upload found.");
        return "";
    }
    WidgetData data = null;
    Iterator<?> it = fileItems.iterator();
    if (it.hasNext()) {
        FileItem fileItem = (FileItem) it.next();
        if (!fileItem.isFormField()) {
            /* The file item contains an uploaded file */
            final String contentType = fileItem.getContentType();
            final byte[] fileData = fileItem.get();
            final String filename = fileItem.getName();
            data = new WidgetData(contentType, filename, fileData);
        }
    }
    Manager.setWidgetData(providerName, uid, dataName, data);
    return String.format(
            "<script type=\"text/javascript\">window.parent.NXThemesWebWidgets.getUploader('%s', '%s', '%s').complete();</script>",
            providerName, uid, dataName);
}

From source file:org.ofbiz.content.content.UploadContentAndImage.java

public static String uploadContentAndImage(HttpServletRequest request, HttpServletResponse response) {
    try {//  w  w  w. j a va 2s .  co m
        Locale locale = UtilHttp.getLocale(request);
        LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
        Delegator delegator = (Delegator) request.getAttribute("delegator");
        HttpSession session = request.getSession();
        GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");

        ServletFileUpload dfu = new ServletFileUpload(
                new DiskFileItemFactory(10240, FileUtil.getFile("runtime/tmp")));
        List<FileItem> lst = null;
        try {
            lst = UtilGenerics.checkList(dfu.parseRequest(request));
        } catch (FileUploadException e4) {
            request.setAttribute("_ERROR_MESSAGE_", e4.getMessage());
            Debug.logError("[UploadContentAndImage.uploadContentAndImage] " + e4.getMessage(), module);
            return "error";
        }
        //if (Debug.infoOn()) Debug.logInfo("[UploadContentAndImage]lst " + lst, module);

        if (lst.size() == 0) {
            String errMsg = UtilProperties.getMessage(UploadContentAndImage.err_resource,
                    "uploadContentAndImage.no_files_uploaded", locale);
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            Debug.logWarning("[DataEvents.uploadImage] No files uploaded", module);
            return "error";
        }

        Map<String, Object> passedParams = FastMap.newInstance();
        FileItem fi = null;
        FileItem imageFi = null;
        byte[] imageBytes = {};
        for (int i = 0; i < lst.size(); i++) {
            fi = lst.get(i);
            //String fn = fi.getName();
            String fieldName = fi.getFieldName();
            if (fi.isFormField()) {
                String fieldStr = fi.getString();
                passedParams.put(fieldName, fieldStr);
            } else if (fieldName.equals("imageData")) {
                imageFi = fi;
                imageBytes = imageFi.get();
            }
        }
        if (Debug.infoOn()) {
            Debug.logInfo("[UploadContentAndImage]passedParams: " + passedParams, module);
        }

        TransactionUtil.begin();
        List<String> contentPurposeList = ContentWorker.prepContentPurposeList(passedParams);
        passedParams.put("contentPurposeList", contentPurposeList);
        String entityOperation = (String) passedParams.get("entityOperation");
        String passedContentId = (String) passedParams.get("ftlContentId");
        List<String> targetOperationList = ContentWorker.prepTargetOperationList(passedParams, entityOperation);
        passedParams.put("targetOperationList", targetOperationList);

        // Create or update FTL template
        Map<String, Object> ftlContext = FastMap.newInstance();
        ftlContext.put("userLogin", userLogin);
        ftlContext.put("contentId", passedParams.get("ftlContentId"));
        ftlContext.put("ownerContentId", passedParams.get("ownerContentId"));
        String contentTypeId = (String) passedParams.get("contentTypeId");
        ftlContext.put("contentTypeId", contentTypeId);
        ftlContext.put("statusId", passedParams.get("statusId"));
        ftlContext.put("contentPurposeList", UtilMisc.toList(passedParams.get("contentPurposeList")));
        ftlContext.put("contentPurposeList", contentPurposeList);
        ftlContext.put("targetOperationList", targetOperationList);
        ftlContext.put("contentName", passedParams.get("contentName"));
        ftlContext.put("dataTemplateTypeId", passedParams.get("dataTemplateTypeId"));
        ftlContext.put("description", passedParams.get("description"));
        ftlContext.put("privilegeEnumId", passedParams.get("privilegeEnumId"));
        String drid = (String) passedParams.get("dataResourceId");
        //if (Debug.infoOn()) Debug.logInfo("[UploadContentAndImage]drid:" + drid, module);
        ftlContext.put("dataResourceId", drid);
        ftlContext.put("dataResourceTypeId", null); // inhibits persistence of DataResource, because it already exists
        String contentIdTo = (String) passedParams.get("contentIdTo");
        ftlContext.put("contentIdTo", contentIdTo);
        String contentAssocTypeId = (String) passedParams.get("contentAssocTypeId");
        ftlContext.put("contentAssocTypeId", null); // Don't post assoc at this time
        Map<String, Object> ftlResults = dispatcher.runSync("persistContentAndAssoc", ftlContext);
        boolean isError = ModelService.RESPOND_ERROR.equals(ftlResults.get(ModelService.RESPONSE_MESSAGE));
        if (isError) {
            request.setAttribute("_ERROR_MESSAGE_", ftlResults.get(ModelService.ERROR_MESSAGE));
            TransactionUtil.rollback();
            return "error";
        }
        String ftlContentId = (String) ftlResults.get("contentId");
        if (UtilValidate.isNotEmpty(contentIdTo)) {
            Map<String, Object> map = FastMap.newInstance();
            map.put("fromDate", UtilDateTime.nowTimestamp());
            map.put("contentId", ftlContentId);
            map.put("contentIdTo", contentIdTo);
            map.put("userLogin", userLogin);
            if (UtilValidate.isEmpty(contentAssocTypeId) && UtilValidate.isEmpty(passedContentId)
                    && UtilValidate.isNotEmpty(contentIdTo)) {
                // switch the association order because we are really not linking to the forum
                // but showing that this content is released to that forum.
                map.put("contentIdTo", ftlContentId);
                map.put("contentId", contentIdTo);
                map.put("contentAssocTypeId", "PUBLISH_RELEASE");
            } else if (contentAssocTypeId.equals("PUBLISH_LINK")) {
                map.put("contentAssocTypeId", "PUBLISH_LINK");
                String publishOperation = (String) passedParams.get("publishOperation");
                if (UtilValidate.isEmpty(publishOperation)) {
                    publishOperation = "CONTENT_PUBLISH";
                }
                map.put("targetOperationList", StringUtil.split(publishOperation, "|"));
                map.put("targetOperationString", null);
            } else {
                map.put("contentAssocTypeId", contentAssocTypeId);
            }
            if (UtilValidate.isNotEmpty(map.get("contentAssocTypeId"))) {
                ftlResults = dispatcher.runSync("createContentAssoc", map);
                isError = ModelService.RESPOND_ERROR.equals(ftlResults.get(ModelService.RESPONSE_MESSAGE));
                if (isError) {
                    request.setAttribute("_ERROR_MESSAGE_", ftlResults.get(ModelService.ERROR_MESSAGE));
                    TransactionUtil.rollback();
                    return "error";
                }
            }
        }

        if (UtilValidate.isEmpty(ftlContentId)) {
            ftlContentId = passedContentId;
        }

        String ftlDataResourceId = drid;

        if (Debug.infoOn())
            Debug.logInfo("[UploadContentAndImage]ftlContentId:" + ftlContentId, module);
        //if (Debug.infoOn()) Debug.logInfo("[UploadContentAndImage]ftlDataResourceId:" + ftlDataResourceId, module);
        // Create or update summary text subContent
        if (passedParams.containsKey("summaryData")) {
            Map<String, Object> sumContext = FastMap.newInstance();
            sumContext.put("userLogin", userLogin);
            sumContext.put("contentId", passedParams.get("sumContentId"));
            sumContext.put("ownerContentId", ftlContentId);
            sumContext.put("contentTypeId", "DOCUMENT");
            sumContext.put("statusId", passedParams.get("statusId"));
            sumContext.put("contentPurposeList", UtilMisc.toList("SUMMARY"));
            //sumContext.put("contentPurposeList", contentPurposeList);
            sumContext.put("targetOperationList", targetOperationList);
            sumContext.put("contentName", passedParams.get("contentName"));
            sumContext.put("description", passedParams.get("description"));
            sumContext.put("privilegeEnumId", passedParams.get("privilegeEnumId"));
            sumContext.put("dataResourceId", passedParams.get("sumDataResourceId"));
            sumContext.put("dataResourceTypeId", "ELECTRONIC_TEXT");
            sumContext.put("contentIdTo", ftlContentId);
            sumContext.put("contentAssocTypeId", "SUB_CONTENT");
            sumContext.put("textData", passedParams.get("summaryData"));
            sumContext.put("mapKey", "SUMMARY");
            sumContext.put("dataTemplateTypeId", "NONE");
            Map<String, Object> sumResults = dispatcher.runSync("persistContentAndAssoc", sumContext);
            isError = ModelService.RESPOND_ERROR.equals(sumResults.get(ModelService.RESPONSE_MESSAGE));
            if (isError) {
                request.setAttribute("_ERROR_MESSAGE_", sumResults.get(ModelService.ERROR_MESSAGE));
                TransactionUtil.rollback();
                return "error";
            }
        }

        // Create or update electronic text subContent
        if (passedParams.containsKey("textData")) {
            Map<String, Object> txtContext = FastMap.newInstance();
            txtContext.put("userLogin", userLogin);
            txtContext.put("contentId", passedParams.get("txtContentId"));
            txtContext.put("ownerContentId", ftlContentId);
            txtContext.put("contentTypeId", "DOCUMENT");
            txtContext.put("statusId", passedParams.get("statusId"));
            //txtContext.put("contentPurposeList", contentPurposeList);
            txtContext.put("contentPurposeList", UtilMisc.toList("MAIN_ARTICLE"));
            txtContext.put("targetOperationList", targetOperationList);
            txtContext.put("contentName", passedParams.get("contentName"));
            txtContext.put("description", passedParams.get("description"));
            txtContext.put("privilegeEnumId", passedParams.get("privilegeEnumId"));
            txtContext.put("dataResourceId", passedParams.get("txtDataResourceId"));
            txtContext.put("dataResourceTypeId", "ELECTRONIC_TEXT");
            txtContext.put("contentIdTo", ftlContentId);
            txtContext.put("contentAssocTypeId", "SUB_CONTENT");
            txtContext.put("textData", passedParams.get("textData"));
            txtContext.put("mapKey", "ARTICLE");
            txtContext.put("dataTemplateTypeId", "NONE");
            Map<String, Object> txtResults = dispatcher.runSync("persistContentAndAssoc", txtContext);
            isError = ModelService.RESPOND_ERROR.equals(txtResults.get(ModelService.RESPONSE_MESSAGE));
            if (isError) {
                request.setAttribute("_ERROR_MESSAGE_", txtResults.get(ModelService.ERROR_MESSAGE));
                TransactionUtil.rollback();
                return "error";
            }
        }

        // Create or update image subContent
        Map<String, Object> imgContext = FastMap.newInstance();
        if (imageBytes.length > 0) {
            imgContext.put("userLogin", userLogin);
            imgContext.put("contentId", passedParams.get("imgContentId"));
            imgContext.put("ownerContentId", ftlContentId);
            imgContext.put("contentTypeId", "DOCUMENT");
            imgContext.put("statusId", passedParams.get("statusId"));
            imgContext.put("contentName", passedParams.get("contentName"));
            imgContext.put("description", passedParams.get("description"));
            imgContext.put("contentPurposeList", contentPurposeList);
            imgContext.put("privilegeEnumId", passedParams.get("privilegeEnumId"));
            imgContext.put("targetOperationList", targetOperationList);
            imgContext.put("dataResourceId", passedParams.get("imgDataResourceId"));
            //String dataResourceTypeId = (String)passedParams.get("dataResourceTypeId");
            //if (UtilValidate.isEmpty(dataResourceTypeId))
            //dataResourceTypeId = "IMAGE_OBJECT";
            String dataResourceTypeId = "IMAGE_OBJECT";
            imgContext.put("dataResourceTypeId", dataResourceTypeId);
            imgContext.put("contentIdTo", ftlContentId);
            imgContext.put("contentAssocTypeId", "SUB_CONTENT");
            imgContext.put("imageData", imageBytes);
            imgContext.put("mapKey", "IMAGE");
            imgContext.put("dataTemplateTypeId", "NONE");
            // String rootDir = request.getSession().getServletContext().getRealPath("/");
            imgContext.put("rootDir", "rootDir");
            if (Debug.infoOn())
                Debug.logInfo("[UploadContentAndImage]imgContext " + imgContext, module);
            Map<String, Object> imgResults = dispatcher.runSync("persistContentAndAssoc", imgContext);
            isError = ModelService.RESPOND_ERROR.equals(imgResults.get(ModelService.RESPONSE_MESSAGE));
            if (isError) {
                request.setAttribute("_ERROR_MESSAGE_", imgResults.get(ModelService.ERROR_MESSAGE));
                TransactionUtil.rollback();
                return "error";
            }
        }

        // Check for existing AUTHOR link
        String userLoginId = userLogin.getString("userLoginId");
        GenericValue authorContent = EntityQuery.use(delegator).from("Content").where("contentId", userLoginId)
                .cache().queryOne();
        if (authorContent != null) {
            long currentAuthorAssocCount = EntityQuery.use(delegator).from("ContentAssoc").where("contentId",
                    ftlContentId, "contentIdTo", userLoginId, "contentAssocTypeId", "AUTHOR").filterByDate()
                    .queryCount();
            //if (Debug.infoOn()) Debug.logInfo("[UploadContentAndImage]currentAuthorAssocList " + currentAuthorAssocList, module);
            if (currentAuthorAssocCount == 0) {
                // Don't want to bother with permission checking on this association
                GenericValue authorAssoc = delegator.makeValue("ContentAssoc");
                authorAssoc.set("contentId", ftlContentId);
                authorAssoc.set("contentIdTo", userLoginId);
                authorAssoc.set("contentAssocTypeId", "AUTHOR");
                authorAssoc.set("fromDate", UtilDateTime.nowTimestamp());
                authorAssoc.set("createdByUserLogin", userLoginId);
                authorAssoc.set("lastModifiedByUserLogin", userLoginId);
                authorAssoc.set("createdDate", UtilDateTime.nowTimestamp());
                authorAssoc.set("lastModifiedDate", UtilDateTime.nowTimestamp());
                authorAssoc.create();
            }
        }

        request.setAttribute("dataResourceId", ftlDataResourceId);
        request.setAttribute("drDataResourceId", ftlDataResourceId);
        request.setAttribute("contentId", ftlContentId);
        request.setAttribute("masterContentId", ftlContentId);
        request.setAttribute("contentIdTo", contentIdTo);
        String newTrail = passedParams.get("nodeTrailCsv") + "," + ftlContentId;
        request.setAttribute("nodeTrailCsv", newTrail);
        request.setAttribute("passedParams", passedParams);
        //if (Debug.infoOn()) Debug.logInfo("[UploadContentAndImage]newTrail: " + newTrail, module);
        TransactionUtil.commit();
    } catch (Exception e) {
        Debug.logError(e, "[UploadContentAndImage] ", module);
        request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
        try {
            TransactionUtil.rollback();
        } catch (GenericTransactionException e2) {
            request.setAttribute("_ERROR_MESSAGE_", e2.getMessage());
            return "error";
        }
        return "error";
    }
    return "success";
}

From source file:org.ofbiz.content.content.UploadContentAndImage.java

public static String uploadContentStuff(HttpServletRequest request, HttpServletResponse response) {
    try {//from   w  ww .ja  va 2  s .com
        HttpSession session = request.getSession();
        GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");

        ServletFileUpload dfu = new ServletFileUpload(
                new DiskFileItemFactory(10240, FileUtil.getFile("runtime/tmp")));
        //if (Debug.infoOn()) Debug.logInfo("[UploadContentAndImage]DiskFileUpload " + dfu, module);
        List<FileItem> lst = null;
        try {
            lst = UtilGenerics.checkList(dfu.parseRequest(request));
        } catch (FileUploadException e4) {
            request.setAttribute("_ERROR_MESSAGE_", e4.getMessage());
            Debug.logError("[UploadContentAndImage.uploadContentAndImage] " + e4.getMessage(), module);
            return "error";
        }
        //if (Debug.infoOn()) Debug.logInfo("[UploadContentAndImage]lst " + lst, module);

        if (lst.size() == 0) {
            request.setAttribute("_ERROR_MESSAGE_", "No files uploaded");
            Debug.logWarning("[DataEvents.uploadImage] No files uploaded", module);
            return "error";
        }

        Map<String, Object> passedParams = FastMap.newInstance();
        FileItem fi = null;
        FileItem imageFi = null;
        byte[] imageBytes = {};
        passedParams.put("userLogin", userLogin);
        for (int i = 0; i < lst.size(); i++) {
            fi = lst.get(i);
            //String fn = fi.getName();
            String fieldName = fi.getFieldName();
            if (fi.isFormField()) {
                String fieldStr = fi.getString();
                passedParams.put(fieldName, fieldStr);
            } else if (fieldName.startsWith("imageData")) {
                imageFi = fi;
                String fileName = fi.getName();
                passedParams.put("drObjectInfo", fileName);
                String contentType = fi.getContentType();
                passedParams.put("drMimeTypeId", contentType);
                imageBytes = imageFi.get();
                passedParams.put(fieldName, imageBytes);
                if (Debug.infoOn()) {
                    Debug.logInfo("[UploadContentAndImage]imageData: " + imageBytes.length, module);
                }
            }
        }
        if (Debug.infoOn()) {
            Debug.logInfo("[UploadContentAndImage]passedParams: " + passedParams, module);
        }

        // The number of multi form rows is retrieved
        int rowCount = UtilHttp.getMultiFormRowCount(request);
        if (rowCount < 1) {
            rowCount = 1;
        }
        TransactionUtil.begin();
        for (int i = 0; i < rowCount; i++) {
            String suffix = "_o_" + i;
            if (i == 0) {
                suffix = "";
            }
            String returnMsg = processContentUpload(passedParams, suffix, request);
            if (returnMsg.equals("error")) {
                try {
                    TransactionUtil.rollback();
                } catch (GenericTransactionException e2) {
                    ServiceUtil.setMessages(request, e2.getMessage(), null, null);
                    return "error";
                }
                return "error";
            }
        }
        TransactionUtil.commit();
    } catch (Exception e) {
        Debug.logError(e, "[UploadContentAndImage] ", module);
        request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
        try {
            TransactionUtil.rollback();
        } catch (GenericTransactionException e2) {
            request.setAttribute("_ERROR_MESSAGE_", e2.getMessage());
            return "error";
        }
        return "error";
    }
    return "success";
}

From source file:org.ofbiz.content.data.DataResourceWorker.java

/**
 * Uploads image data from a form and stores it in ImageDataResource. Expects key data in a field identified by the "idField" value and the binary data
 * to be in a field id'd by uploadField.
 *//*from   w  w  w .j a  v  a2 s. c o m*/
// TODO: This method is not used and should be removed. amb
public static String uploadAndStoreImage(HttpServletRequest request, String idField, String uploadField) {
    //Delegator delegator = (Delegator) request.getAttribute("delegator");

    //String idFieldValue = null;
    ServletFileUpload fu = new ServletFileUpload(
            new DiskFileItemFactory(10240, FileUtil.getFile("runtime/tmp")));
    List<FileItem> lst = null;
    Locale locale = UtilHttp.getLocale(request);

    try {
        lst = UtilGenerics.checkList(fu.parseRequest(request));
    } catch (FileUploadException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.toString());
        return "error";
    }

    if (lst.size() == 0) {
        String errMsg = UtilProperties.getMessage(DataResourceWorker.err_resource,
                "dataResourceWorker.no_files_uploaded", locale);
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        Debug.logWarning("[DataEvents.uploadImage] No files uploaded", module);
        return "error";
    }

    // This code finds the idField and the upload FileItems
    FileItem fi = null;
    FileItem imageFi = null;
    String imageFileName = null;
    Map<String, Object> passedParams = FastMap.newInstance();
    HttpSession session = request.getSession();
    GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
    passedParams.put("userLogin", userLogin);
    byte[] imageBytes = null;
    for (int i = 0; i < lst.size(); i++) {
        fi = lst.get(i);
        //String fn = fi.getName();
        String fieldName = fi.getFieldName();
        if (fi.isFormField()) {
            String fieldStr = fi.getString();
            passedParams.put(fieldName, fieldStr);
        } else if (fieldName.startsWith("imageData")) {
            imageFi = fi;
            imageBytes = imageFi.get();
            passedParams.put(fieldName, imageBytes);
            imageFileName = imageFi.getName();
            passedParams.put("drObjectInfo", imageFileName);
            if (Debug.infoOn())
                Debug.logInfo("[UploadContentAndImage]imageData: " + imageBytes.length, module);
        }
    }

    if (imageBytes != null && imageBytes.length > 0) {
        String mimeType = getMimeTypeFromImageFileName(imageFileName);
        if (UtilValidate.isNotEmpty(mimeType)) {
            passedParams.put("drMimeTypeId", mimeType);
            try {
                String returnMsg = UploadContentAndImage.processContentUpload(passedParams, "", request);
                if (returnMsg.equals("error")) {
                    return "error";
                }
            } catch (GenericServiceException e) {
                request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
                return "error";
            }
        } else {
            request.setAttribute("_ERROR_MESSAGE_", "mimeType is empty.");
            return "error";
        }
    }
    return "success";
}

From source file:org.ofbiz.content.layout.LayoutWorker.java

/**
 * Uploads image data from a form and stores it in ImageDataResource.
 * Expects key data in a field identitified by the "idField" value
 * and the binary data to be in a field id'd by uploadField.
 *///from ww w .jav  a2s  .c om
public static Map<String, Object> uploadImageAndParameters(HttpServletRequest request, String uploadField) {

    //Debug.logVerbose("in uploadAndStoreImage", "");
    Locale locale = UtilHttp.getLocale(request);

    Map<String, Object> results = FastMap.newInstance();
    Map<String, String> formInput = FastMap.newInstance();
    results.put("formInput", formInput);
    ServletFileUpload fu = new ServletFileUpload(
            new DiskFileItemFactory(10240, new File(new File("runtime"), "tmp")));
    List<FileItem> lst = null;
    try {
        lst = UtilGenerics.checkList(fu.parseRequest(request));
    } catch (FileUploadException e4) {
        return ServiceUtil.returnError(e4.getMessage());
    }

    if (lst.size() == 0) {
        String errMsg = UtilProperties.getMessage(err_resource, "layoutEvents.no_files_uploaded", locale);
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        //Debug.logWarning("[DataEvents.uploadImage] No files uploaded", module);
        return ServiceUtil
                .returnError(UtilProperties.getMessage(err_resource, "layoutEvents.no_files_uploaded", locale));
    }

    // This code finds the idField and the upload FileItems
    FileItem fi = null;
    FileItem imageFi = null;
    for (int i = 0; i < lst.size(); i++) {
        fi = lst.get(i);
        String fieldName = fi.getFieldName();
        String fieldStr = fi.getString();
        if (fi.isFormField()) {
            formInput.put(fieldName, fieldStr);
            request.setAttribute(fieldName, fieldStr);
            //Debug.logVerbose("in uploadAndStoreImage, fieldName:" + fieldName + " fieldStr:" + fieldStr, "");
        }
        if (fieldName.equals(uploadField)) {
            imageFi = fi;
            //MimeType of upload file
            results.put("uploadMimeType", fi.getContentType());
        }
    }

    if (imageFi == null) {
        String errMsg = UtilProperties.getMessage(err_resource, "layoutEvents.image_null",
                UtilMisc.toMap("imageFi", imageFi), locale);
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        //Debug.logWarning("[DataEvents.uploadImage] imageFi(" + imageFi + ") is null", module);
        return null;
    }

    byte[] imageBytes = imageFi.get();
    ByteBuffer byteWrap = ByteBuffer.wrap(imageBytes);
    results.put("imageData", byteWrap);
    results.put("imageFileName", imageFi.getName());

    //Debug.logVerbose("in uploadAndStoreImage, results:" + results, "");
    return results;
}