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:net.morphbank.mbsvc3.webservices.Uploader.java

private String saveTempFile(FileItem item) {
    FileOutputStream outputStream;
    String filename = "";

    if (item.getName().endsWith(".xls")) {
        filename = folderPath + "temp.xls";
    } else {/*  w w w .j  a  v  a2  s  .  c  o m*/
        filename = folderPath + "temp.csv";
    }
    try {
        outputStream = new FileOutputStream(filename);
        outputStream.write(item.get());
        outputStream.close();
        return folderPath;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.tasktop.c2c.server.internal.wiki.server.WikiServiceController.java

@Section(value = "Attachments")
@Title("Upload Attachment")
@Secured({ Role.Community, Role.User, Role.Admin })
@RequestMapping(value = "{pageId}/attachment", method = RequestMethod.POST)
public void uploadAttachment(@PathVariable(value = "pageId") Integer pageId, HttpServletRequest request,
        HttpServletResponse response) throws IOException, FileUploadException, TextHtmlContentExceptionWrapper {

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<Attachment> attachments = new ArrayList<Attachment>();
    Map<String, String> formValues = new HashMap<String, String>();

    PageHandle pageHandle = new PageHandle(pageId);
    try {// w  w w  .j a  v a  2 s. co  m
        // find all existing attachments
        List<Attachment> allPageAttachments = service.listAttachments(pageId);
        // map them by name
        Map<String, Attachment> attachmentByName = new HashMap<String, Attachment>();
        for (Attachment attachment : allPageAttachments) {
            attachmentByName.put(attachment.getName(), attachment);
        }

        // inspect the request, getting all posted attachments
        @SuppressWarnings("unchecked")
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) {

            if (item.isFormField()) {
                formValues.put(item.getFieldName(), item.getString());
            } else {
                Attachment attachment = new Attachment();
                attachment.setPage(pageHandle);
                attachment.setContent(item.get());
                attachment.setName(item.getName());
                attachment.setMimeType(item.getContentType());
                attachments.add(attachment);
            }
        }

        // for each new attachment, either create or update
        for (Attachment attachment : attachments) {
            Attachment attach = attachmentByName.get(attachment.getName());
            if (attach != null) {
                attachment.setId(attach.getId());
                service.updateAttachment(attachment);
            } else {
                service.createAttachment(attachment);
            }
        }

        // get content for response
        allPageAttachments = service.listAttachments(pageId);
        Page page = service.retrievePage(pageId);
        page.setContent(null);

        response.setContentType("text/html");
        response.getWriter().write(jsonMapper.writeValueAsString(
                Collections.singletonMap("uploadResult", new UploadResult(page, allPageAttachments))));
    } catch (Exception e) {
        throw new TextHtmlContentExceptionWrapper(e.getMessage(), e);
    }
}

From source file:eu.impact_project.wsclient.SOAPresults.java

/**
 * Loads the user values/files and sends them to the web service. Files are
 * encoded to Base64. Stores the resulting message in the session and the
 * resulting files on the server.//from w w  w .  j a  v  a  2 s .  c om
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    OutputStream outStream = null;
    BufferedInputStream bis = null;
    user = request.getParameter("user");
    pass = request.getParameter("pass");

    try {

        HttpSession session = request.getSession(true);

        String folder = session.getServletContext().getRealPath("/");
        if (!folder.endsWith("/")) {
            folder = folder + "/";
        }

        Properties props = new Properties();
        InputStream stream = new URL("file:" + folder + "config.properties").openStream();

        props.load(stream);
        stream.close();

        boolean loadDefault = Boolean.parseBoolean(props.getProperty("loadDefaultWebService"));
        boolean supportFileUpload = Boolean.parseBoolean(props.getProperty("supportFileUpload"));
        boolean oneResultFile = Boolean.parseBoolean(props.getProperty("oneResultFile"));
        String defaultFilePrefix = props.getProperty("defaultFilePrefix");

        SoapService serviceObject = (SoapService) session.getAttribute("serviceObject");
        SoapOperation operation = null;
        if (supportFileUpload) {

            // stores all the strings and encoded files from the html form
            Map<String, String> htmlFormItems = new HashMap<String, String>();

            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List /* FileItem */ items = upload.parseRequest(request);

            // Process the uploaded items
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                // a normal string field
                if (item.isFormField()) {
                    htmlFormItems.put(item.getFieldName(), item.getString());

                    // uploaded file
                } else {

                    // encode the uploaded file to base64
                    String currentAttachment = new String(Base64.encode(item.get()));

                    htmlFormItems.put(item.getFieldName(), currentAttachment);
                }
            }

            // get the chosen WSDL operation
            String operationName = htmlFormItems.get("operationName");

            operation = serviceObject.getOperation(operationName);
            for (SoapInput input : operation.getInputs()) {
                input.setValue(htmlFormItems.get(input.getName()));
            }

        } else {
            // get the chosen WSDL operation
            String operationName = request.getParameter("operationName");

            operation = serviceObject.getOperation(operationName);
            for (SoapInput input : operation.getInputs()) {
                String[] soapInputValues = request.getParameterValues(input.getName());
                input.clearValues();
                for (String value : soapInputValues) {
                    input.addValue(value);
                }
            }

        }

        List<SoapOutput> outs = operation.execute(user, pass);
        String soapResponse = operation.getResponse();

        String htmlResponse = useXslt(soapResponse, "/SoapToHtml.xsl");

        session.setAttribute("htmlResponse", htmlResponse);
        session.setAttribute("soapResponse", soapResponse);

        // for giving the file names back to the JSP
        List<String> fileNames = new ArrayList<String>();

        // process possible attachments in the response
        List<SoapAttachment> attachments = operation.getReceivedAttachments();
        int i = 0;
        for (SoapAttachment attachment : attachments) {

            // path to the server directory
            String serverPath = getServletContext().getRealPath("/");
            if (!serverPath.endsWith("/")) {
                serverPath = folder + "/";
            }

            // construct the file name for the attachment
            String fileEnding = "";
            String contentType = attachment.getContentType();
            System.out.println("content type: " + contentType);
            if (contentType.equals("image/gif")) {
                fileEnding = ".gif";
            } else if (contentType.equals("image/jpeg")) {
                fileEnding = ".jpg";
            } else if (contentType.equals("image/tiff")) {
                fileEnding = ".tif";
            } else if (contentType.equals("application/vnd.ms-excel")) {
                fileEnding = ".xlsx";
            }

            String fileName = loadDefault ? defaultFilePrefix : "attachedFile";

            String counter = oneResultFile ? "" : i + "";

            String attachedFileName = fileName + counter + fileEnding;

            // store the attachment into the file
            File file = new File(serverPath + attachedFileName);
            outStream = new FileOutputStream(file);

            InputStream inStream = attachment.getInputStream();

            bis = new BufferedInputStream(inStream);

            int bufSize = 1024 * 8;

            byte[] bytes = new byte[bufSize];

            int count = bis.read(bytes);
            while (count != -1 && count <= bufSize) {
                outStream.write(bytes, 0, count);
                count = bis.read(bytes);
            }
            if (count != -1) {
                outStream.write(bytes, 0, count);
            }
            outStream.close();
            bis.close();

            fileNames.add(attachedFileName);
            i++;
        }

        // pass the file names to JSP
        request.setAttribute("fileNames", fileNames);

        request.setAttribute("round3", "round3");
        // get back to JSP
        RequestDispatcher rd = getServletContext().getRequestDispatcher("/interface.jsp");
        rd.forward(request, response);

    } catch (Exception e) {
        logger.error("Exception", e);
        e.printStackTrace();
    } finally {
        if (outStream != null) {
            outStream.close();
        }
        if (bis != null) {
            bis.close();
        }
    }

}

From source file:com.glaf.mail.web.rest.MailTaskResource.java

@POST
@Path("/uploadMails")
@ResponseBody//from   w  ww .  jav  a 2  s  .  co  m
public void uploadMails(@Context HttpServletRequest request, @Context UriInfo uriInfo) {
    Map<String, Object> params = RequestUtils.getParameterMap(request);
    logger.debug(params);
    String taskId = request.getParameter("taskId");
    if (StringUtils.isEmpty(taskId)) {
        taskId = request.getParameter("id");
    }
    MailTask mailTask = null;
    if (StringUtils.isNotEmpty(taskId)) {
        mailTask = mailTaskService.getMailTask(taskId);
    }

    if (mailTask != null && StringUtils.equals(RequestUtils.getActorId(request), mailTask.getCreateBy())) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(4096);
        // 
        factory.setRepository(new File(SystemProperties.getConfigRootPath() + "/temp/"));
        ServletFileUpload upload = new ServletFileUpload(factory);
        // ?
        // 
        // upload.setSizeMax(4194304);
        upload.setHeaderEncoding("UTF-8");
        List<?> fileItems = null;
        try {
            fileItems = upload.parseRequest(request);
            Iterator<?> i = fileItems.iterator();
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                logger.debug(fi.getName());
                if (fi.getName().endsWith(".txt")) {
                    byte[] bytes = fi.get();
                    String rowIds = new String(bytes);
                    List<String> addresses = StringTools.split(rowIds);
                    if (addresses.size() <= 100000) {
                        mailDataFacede.saveMails(taskId, addresses);
                        taskId = mailTask.getId();

                        if (mailTask.getLocked() == 0) {
                            QuartzUtils.stop(taskId);
                            QuartzUtils.restart(taskId);
                        } else {
                            QuartzUtils.stop(taskId);
                        }

                    } else {
                        throw new RuntimeException("mail addresses too many");
                    }
                    break;
                }
            }
        } catch (FileUploadException ex) {// ?
            ex.printStackTrace();
            throw new RuntimeException(ex.getMessage());
        }
    }
}

From source file:com.kmetop.demsy.modules.ckfinder.FileUploadCommand.java

/**
 * saves temporary file in the correct file path.
 * // w ww .j a  va 2  s.c om
 * @param path
 *            path to save file
 * @param item
 *            file upload item
 * @return result of saving, true if saved correctly
 * @throws Exception
 *             when error occurs.
 */
private boolean saveTemporaryFile(final String path, final FileItem item) throws Exception {
    File file = new File(path, this.newFileName);

    AfterFileUploadEventArgs args = new AfterFileUploadEventArgs();
    args.setCurrentFolder(this.currentFolder);
    args.setFile(file);
    args.setFileContent(item.get());
    if (!ImageUtils.isImage(file)) {
        item.write(file);
        if (configuration.getEvents() != null) {
            configuration.getEvents().run(EventTypes.AfterFileUpload, args, configuration);
        }
        return true;
    } else if (ImageUtils.checkImageSize(item.getInputStream(), this.configuration)) {

        ImageUtils.createTmpThumb(item.getInputStream(), file, getFileItemName(item), this.configuration);
        if (configuration.getEvents() != null) {
            configuration.getEvents().run(EventTypes.AfterFileUpload, args, configuration);
        }
        return true;
    } else if (configuration.checkSizeAfterScaling()) {
        ImageUtils.createTmpThumb(item.getInputStream(), file, getFileItemName(item), this.configuration);
        if (FileUtils.checkFileSize(configuration.getTypes().get(this.type), file.length())) {
            if (configuration.getEvents() != null) {
                configuration.getEvents().run(EventTypes.AfterFileUpload, args, configuration);
            }
            return true;
        } else {
            file.delete();
            this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG;
            return false;
        }
    }
    // should be unreacheable
    return false;
}

From source file:com.amazonaws.serverless.proxy.internal.servlet.AwsProxyHttpServletRequest.java

private Map<String, Part> getMultipartFormParametersMap() {
    if (!ServletFileUpload.isMultipartContent(this)) { // isMultipartContent also checks the content type
        return new HashMap<>();
    }/*from  ww w.  j  av  a 2s .c om*/

    Map<String, Part> output = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);

    ServletFileUpload upload = new ServletFileUpload();
    try {
        List<FileItem> items = upload.parseRequest(this);
        for (FileItem item : items) {
            AwsProxyRequestPart newPart = new AwsProxyRequestPart(item.get());
            newPart.setName(item.getName());
            newPart.setSubmittedFileName(item.getFieldName());
            newPart.setContentType(item.getContentType());
            newPart.setSize(item.getSize());

            Iterator<String> headerNamesIterator = item.getHeaders().getHeaderNames();
            while (headerNamesIterator.hasNext()) {
                String headerName = headerNamesIterator.next();
                Iterator<String> headerValuesIterator = item.getHeaders().getHeaders(headerName);
                while (headerValuesIterator.hasNext()) {
                    newPart.addHeader(headerName, headerValuesIterator.next());
                }
            }

            output.put(item.getFieldName(), newPart);
        }
    } catch (FileUploadException e) {
        // TODO: Should we swallaw this?
        e.printStackTrace();
    }
    return output;
}

From source file:fr.paris.lutece.plugins.genericattributes.service.entrytype.AbstractEntryTypeImage.java

/**
 * Do check that an uploaded file is an image
 * @param fileItem The file item/* ww w. j a  v  a2  s . co m*/
 * @param entry the entry
 * @param locale The locale
 * @return The error if any, or null if the file is a valid image
 */
public GenericAttributeError doCheckforImages(FileItem fileItem, Entry entry, Locale locale) {
    String strFilename = FileUploadService.getFileNameOnly(fileItem);
    BufferedImage image = null;

    try {
        if (fileItem.get() != null) {
            image = ImageIO.read(new ByteArrayInputStream(fileItem.get()));
        }
    } catch (IOException e) {
        AppLogService.error(e);
    }

    if ((image == null) && StringUtils.isNotBlank(strFilename)) {
        GenericAttributeError genAttError = new GenericAttributeError();
        genAttError.setMandatoryError(false);

        Object[] args = { fileItem.getName() };
        genAttError.setErrorMessage(I18nService.getLocalizedString(MESSAGE_ERROR_NOT_AN_IMAGE, args, locale));
        genAttError.setTitleQuestion(entry.getTitle());

        return genAttError;
    }

    return null;
}

From source file:it.eng.spagobi.tools.catalogue.service.SaveArtifactAction.java

private Content getContentFromRequest() {
    Content content = null;/*from   w w w .ja v a  2  s .c  om*/
    FileItem uploaded = (FileItem) getAttribute("UPLOADED_FILE");
    if (uploaded != null && uploaded.getSize() > 0) {
        checkUploadedFile(uploaded);
        String fileName = GeneralUtilities.getRelativeFileNames(uploaded.getName());
        content = new Content();
        content.setActive(new Boolean(true));
        UserProfile userProfile = (UserProfile) this.getUserProfile();
        content.setCreationUser(userProfile.getUserId().toString());
        content.setCreationDate(new Date());
        content.setDimension(Long.toString(uploaded.getSize() / 1000) + " KByte");
        content.setFileName(fileName);
        byte[] uplCont = uploaded.get();
        content.setContent(uplCont);
    } else {
        logger.debug("Uploaded file missing or it is empty");
    }
    return content;
}

From source file:de.suse.swamp.modules.actions.DatapackActions.java

public static boolean storeFile(Databit dbit, boolean overwrite, FileItem fi, String uname) throws Exception {
    // skip empty uploads: 
    if (fi != null && !fi.getName().trim().equals("") && fi.getSize() > 0) {
        String fileDir = new SWAMPAPI().doGetProperty("ATTACHMENT_DIR", uname);

        if (!(new File(fileDir)).canWrite()) {
            throw new Exception("Cannot write to configured path: " + fileDir);
        }/*from www  .j a  v  a2s  .c o m*/

        String fileName = fi.getName();
        // fix for browsers setting complete path as name: 
        if (fileName.indexOf("/") >= 0)
            fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
        if (fileName.indexOf("\\") >= 0)
            fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);

        File file = new File(fileDir + fs + dbit.getId() + "-" + fileName);
        if (!overwrite) {
            if (!file.createNewFile()) {
                throw new Exception("Cannot write to file: " + file.getName() + ". File already exists?");
            }
        } else {
            if (file.exists()) {
                file.delete();
            }
            // if its a file with a new name, delete the old one: 
            File oldFile = new File(fileDir + fs + dbit.getId() + "-" + dbit.getValue());
            if (oldFile.exists()) {
                Logger.DEBUG("Deleting old file: " + oldFile.getPath());
                oldFile.delete();
            }
        }

        FileOutputStream stream = new FileOutputStream(file);
        stream.write(fi.get());
        stream.close();
        return true;
    } else {
        return false;
    }
}

From source file:fr.paris.lutece.plugins.directory.utils.DirectoryUtils.java

/**
 * Do download a file//from www.  j  ava 2  s .  c  o  m
 *
 * @param strUrl
 *            the url of the file to download
 * @return a {@link FileItem}
 */
public static File doDownloadFile(String strUrl) {
    FileItem fileItem = null;
    File file = null;
    DirectoryAsynchronousUploadHandler handler = DirectoryAsynchronousUploadHandler.getHandler();

    try {
        fileItem = handler.doDownloadFile(strUrl);
    } catch (BlobStoreClientException e) {
        AppLogService.error(e);
    }

    if (fileItem != null) {
        if (fileItem.getSize() < Integer.MAX_VALUE) {
            PhysicalFile physicalFile = new PhysicalFile();
            physicalFile.setValue(fileItem.get());

            String strFileName = fileItem.getName();

            if (StringUtils.isNotBlank(strFileName)) {
                String strExtension = StringUtils.EMPTY;
                int nLastIndexOfDot = strFileName.lastIndexOf(CONSTANT_DOT);

                if (nLastIndexOfDot != DirectoryUtils.CONSTANT_ID_NULL) {
                    strExtension = strFileName.substring(nLastIndexOfDot + 1);
                }

                file = new File();
                file.setPhysicalFile(physicalFile);
                file.setSize((int) fileItem.getSize());
                file.setTitle(strFileName);

                if (StringUtils.isNotBlank(fileItem.getContentType())) {
                    file.setMimeType(fileItem.getContentType());
                } else {
                    file.setMimeType(FileSystemUtil.getMIMEType(strFileName));
                }

                file.setExtension(strExtension);
            }
        } else {
            AppLogService.error(
                    "DirectoryUtils : File too big ! fr.paris.lutece.plugins.directory.business.File.setSize "
                            + "must have Integer parameter, in other words a size lower than '"
                            + Integer.MAX_VALUE + "'");
        }
    }

    return file;
}