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

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

Introduction

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

Prototype

InputStream getInputStream() throws IOException;

Source Link

Document

Returns an java.io.InputStream InputStream that can be used to retrieve the contents of the file.

Usage

From source file:edu.lternet.pasta.portal.MetadataPreviewerServlet.java

private String processUploadedFile(FileItem item) throws Exception {

    String eml = null;//from   ww w  .  j  a v a 2s  . c o  m

    // Process a file upload
    if (!item.isFormField()) {
        InputStream uploadedStream = item.getInputStream();
        eml = IOUtils.toString(uploadedStream);
        uploadedStream.close();
    }

    return eml;
}

From source file:mx.org.cedn.avisosconagua.engine.processors.Pronostico.java

/**
 * Processes an uploaded file and stores it in MongoDB.
 * @param item file item from the parsed servlet request
 * @param currentId ID for the current MongoDB object for the advice
 * @return file name//  ww  w.  j  av  a  2  s.c o  m
 * @throws IOException 
 */
private String processUploadedFile(FileItem item, String currentId) throws IOException {
    GridFS gridfs = MongoInterface.getInstance().getImagesFS();
    GridFSInputFile gfsFile = gridfs.createFile(item.getInputStream());
    String filename = currentId + ":" + item.getFieldName() + "_" + item.getName();
    gfsFile.setFilename(filename);
    gfsFile.setContentType(item.getContentType());
    gfsFile.save();
    return filename;
}

From source file:com.google.jenkins.plugins.credentials.oauth.JsonServiceAccountConfig.java

@DataBoundConstructor
public JsonServiceAccountConfig(FileItem jsonKeyFile, String prevJsonKeyFile) {
    if (jsonKeyFile != null && jsonKeyFile.getSize() > 0) {
        try {//from  w w  w .  jav  a  2s  .  c om
            JsonKey jsonKey = JsonKey.load(new JacksonFactory(), jsonKeyFile.getInputStream());
            if (jsonKey.getClientEmail() != null && jsonKey.getPrivateKey() != null) {
                try {
                    this.jsonKeyFile = writeJsonKeyToFile(jsonKey);
                } catch (IOException e) {
                    LOGGER.log(Level.SEVERE, "Failed to write json key to file", e);
                }
            }
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, "Failed to read json key from file", e);
        }
    } else if (prevJsonKeyFile != null && !prevJsonKeyFile.isEmpty()) {
        this.jsonKeyFile = prevJsonKeyFile;
    }
}

From source file:com.skin.generator.action.UploadTestAction.java

/**
 * @throws IOException/*from ww  w.  j a  v  a 2 s. com*/
 * @throws ServletException
 */
@UrlPattern("/upload/test2.html")
public void test2() throws IOException, ServletException {
    logger.info("method: " + this.request.getMethod() + " " + this.request.getRequestURI() + " "
            + this.request.getQueryString());

    /**
     * cross domain support
     */
    this.doOptions(this.request, this.response);

    /**
      * preflight
     */
    if (this.request.getMethod().equalsIgnoreCase("OPTIONS")) {
        logger.info("options: " + this.request.getHeader("Origin"));
        return;
    }

    String home = this.servletContext.getRealPath("/WEB-INF/tmp");
    Map<String, Object> result = new HashMap<String, Object>();
    RandomAccessFile raf = null;
    InputStream inputStream = null;

    try {
        Map<String, Object> map = this.parse(this.request);
        int start = Integer.parseInt((String) map.get("start"));
        int end = Integer.parseInt((String) map.get("end"));
        int length = Integer.parseInt((String) map.get("length"));
        FileItem fileItem = (FileItem) map.get("fileData");

        inputStream = fileItem.getInputStream();
        raf = new RandomAccessFile(new File(home, fileItem.getName()), "rw");
        raf.seek(start);
        String partMd5 = copy(inputStream, raf, 4096);

        if (end >= length) {
            String fileMd5 = Hex.encode(Digest.md5(new File(home, fileItem.getName())));
            result.put("fileMd5", fileMd5);
        }

        result.put("status", 200);
        result.put("message", "??");
        result.put("start", end);
        result.put("partMD5", partMd5);
        JsonUtil.callback(this.request, this.response, result);
        return;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        result.put("status", 500);
        result.put("message", "?");
        JsonUtil.callback(this.request, this.response, result);
        return;
    } finally {
        close(raf);
        close(inputStream);
    }
}

From source file:com.liferay.apio.architect.impl.jaxrs.json.reader.MultipartBodyMessageBodyReader.java

private void _storeFileItem(FileItem fileItem, Consumer<String> valueConsumer,
        Consumer<BinaryFile> fileConsumer) throws IOException {

    if (fileItem.isFormField()) {
        InputStream stream = fileItem.getInputStream();

        valueConsumer.accept(Streams.asString(stream));
    } else {/* ww  w.  j a va 2  s  .c om*/
        BinaryFile binaryFile = new BinaryFile(fileItem.getInputStream(), fileItem.getSize(),
                fileItem.getContentType());

        fileConsumer.accept(binaryFile);
    }
}

From source file:br.com.caelum.vraptor.observer.upload.CommonsUploadMultipartObserver.java

protected void processFile(FileItem item, String name, MutableRequest request) {
    try {/*from ww  w.j  a v a 2  s  .co  m*/
        String fileName = FilenameUtils.getName(item.getName());
        UploadedFile upload = new DefaultUploadedFile(item.getInputStream(), fileName, item.getContentType(),
                item.getSize());
        request.setParameter(name, name);
        request.setAttribute(name, upload);

        logger.debug("Uploaded file: {} with {}", name, upload);
    } catch (IOException e) {
        throw new InvalidParameterException("Cant parse uploaded file " + item.getName(), e);
    }
}

From source file:at.ac.tuwien.dsg.cloudlyra.utils.Uploader.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/* w ww . ja  v  a  2s  .  co  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    InputStream dafFileContent = null;
    String dafName = "";
    String dafType = "";

    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    dafName = new File(item.getName()).getName();
                    dafFileContent = item.getInputStream();

                } else {

                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString();

                    if (fieldName.equals("type")) {
                        dafType = fieldValue;
                    }

                    // String log = "att name: " + fieldname + " - value: " + fieldvalue;
                    // Logger.getLogger(Uploader.class.getName()).log(Level.INFO, log);

                }
            }

            //File uploaded successfully
            request.setAttribute("message", "File Uploaded Successfully");
        } catch (Exception ex) {
            request.setAttribute("message", "File Upload Failed due to " + ex);
        }

    } else {
        request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }

    if (!dafName.equals("")) {

        DafStore dafStore = new DafStore();
        dafStore.insertDAF(dafName, dafType, dafFileContent);
        Logger.getLogger(Uploader.class.getName()).log(Level.INFO, dafName);
    }

    response.sendRedirect("daf.jsp");
}

From source file:com.carolinarollergirls.scoreboard.jetty.MediaServlet.java

protected void processZipFileItem(FileItemFactory factory, FileItem zip, List<FileItem> fileItems)
        throws IOException {
    ZipInputStream ziS = new ZipInputStream(zip.getInputStream());
    ZipEntry zE;/*from   www.  j  av a2  s  . co  m*/
    try {
        while (null != (zE = ziS.getNextEntry())) {
            if (zE.isDirectory() || !uploadFileNameFilter.accept(null, zE.getName()))
                continue;
            FileItem item = factory.createItem(null, null, false, zE.getName());
            OutputStream oS = item.getOutputStream();
            IOUtils.copyLarge(ziS, oS);
            oS.close();
            fileItems.add(item);
        }
    } finally {
        ziS.close();
    }
}

From source file:azkaban.web.JobManagerServlet.java

private File unzipFile(FileItem item) throws ServletException, IOException {
    File temp = File.createTempFile("job-temp", ".zip");
    temp.deleteOnExit();// w w w . ja  v a 2  s  . co m
    OutputStream out = new BufferedOutputStream(new FileOutputStream(temp));
    IOUtils.copy(item.getInputStream(), out);
    out.close();
    ZipFile zipfile = new ZipFile(temp);
    File unzipped = Utils.createTempDir(new File(_tempDir));
    Utils.unzip(zipfile, unzipped);
    temp.delete();
    return unzipped;
}

From source file:br.com.caelum.vraptor.interceptor.multipart.MultipartItemsProcessor.java

public void process() {
    Multimap<String, String> params = LinkedListMultimap.create();
    for (FileItem item : items) {
        if (item.isFormField()) {
            params.put(item.getFieldName(), getValue(item));
            continue;
        }//w w w  . j  a  v a 2  s. c o m
        if (notEmpty(item)) {
            try {
                UploadedFile fileInformation = new DefaultUploadedFile(item.getInputStream(), item.getName(),
                        item.getContentType());
                parameters.setParameter(item.getFieldName(), item.getName());
                request.setAttribute(item.getName(), fileInformation);

                logger.debug("Uploaded file: {} with {}", item.getFieldName(), fileInformation);
            } catch (Exception e) {
                throw new InvalidParameterException("Cant parse uploaded file " + item.getName(), e);
            }
        } else {
            logger.debug("A file field was empty: {}", item.getFieldName());
        }
    }
    for (String paramName : params.keySet()) {
        Collection<String> paramValues = params.get(paramName);
        parameters.setParameter(paramName, paramValues.toArray(new String[paramValues.size()]));
    }
}