Example usage for org.apache.commons.fileupload FileItemStream openStream

List of usage examples for org.apache.commons.fileupload FileItemStream openStream

Introduction

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

Prototype

InputStream openStream() throws IOException;

Source Link

Document

Creates an InputStream , which allows to read the items contents.

Usage

From source file:com.medallia.spider.api.DynamicInputImpl.java

/**
 * Creates a new {@link DynamicInputImpl}
 * @param request from which to read the request parameters
 *///from w  w  w .  j  a v a 2 s . c  om
public DynamicInputImpl(HttpServletRequest request) {
    @SuppressWarnings("unchecked")
    Map<String, String[]> reqParams = Maps.newHashMap(request.getParameterMap());
    this.inputParams = reqParams;
    if (ServletFileUpload.isMultipartContent(request)) {
        this.fileUploads = Maps.newHashMap();
        Multimap<String, String> inputParamsWithList = ArrayListMultimap.create();

        ServletFileUpload upload = new ServletFileUpload();
        try {
            FileItemIterator iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                String fieldName = item.getFieldName();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    inputParamsWithList.put(fieldName, Streams.asString(stream, Charsets.UTF_8.name()));
                } else {
                    final String filename = item.getName();
                    final byte[] bytes = ByteStreams.toByteArray(stream);
                    fileUploads.put(fieldName, new UploadedFile() {
                        @Override
                        public String getFilename() {
                            return filename;
                        }

                        @Override
                        public byte[] getBytes() {
                            return bytes;
                        }

                        @Override
                        public int getSize() {
                            return bytes.length;
                        }
                    });
                }
            }
            for (Entry<String, Collection<String>> entry : inputParamsWithList.asMap().entrySet()) {
                inputParams.put(entry.getKey(), entry.getValue().toArray(new String[0]));
            }
        } catch (IOException | FileUploadException e) {
            throw new IllegalArgumentException("Failed to parse multipart", e);
        }
    } else {
        this.fileUploads = Collections.emptyMap();
    }
}

From source file:com.bristle.javalib.net.http.MultiPartFormDataParamMap.java

/**************************************************************************
* Parse the specified HTTP request, initializing the map, and calling 
* the specified callback (if not null) for each file (if any) in the 
* streamed HTTP request. //from   w  w w. j ava2 s  .  c  om
*
*@param request              The HTTP request
*@param callback             The callback class
*@throws FileUploadException When the request is badly formed.
*@throws IOException         When an I/O error occurs reading the request.
*@throws Throwable           When thrown by the callback.
**************************************************************************/
public void parseRequestStream(HttpServletRequest request, FileItemStreamCallBack callback)
        throws FileUploadException, IOException, Throwable {
    if (ServletFileUpload.isMultipartContent(request)) {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream fileItemStream = iter.next();
            if (fileItemStream.isFormField()) {
                String strParamName = fileItemStream.getFieldName();
                InputStream streamIn = fileItemStream.openStream();
                String strParamValue = Streams.asString(streamIn);
                put(strParamName, strParamValue);
                // Note: Can't do the following usefully.  The Parameter 
                //       Map of the HTTP Request is effectively readonly.
                //       This does not report an error, but is a no-op.
                // request.getParameterMap().put(strParamName, strParamValue);
            } else {
                if (callback != null) {
                    callback.fullyProcessAFileItemStream(fileItemStream);
                }
            }
        }
    } else {
        putAll(request.getParameterMap());
    }
}

From source file:jhi.buntata.server.DatasourceIcon.java

@Put
public void putImage(Representation entity) {
    if (entity != null && MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {
        try {/*  w  w w.  j a  v  a2  s .  c  o m*/
            DiskFileItemFactory factory = new DiskFileItemFactory();
            RestletFileUpload upload = new RestletFileUpload(factory);
            FileItemIterator fileIterator = upload.getItemIterator(entity);

            if (fileIterator.hasNext()) {
                FileItemStream fi = fileIterator.next();

                String name = fi.getName();

                File file = new File(dataDir, name);

                int i = 1;
                while (file.exists())
                    file = new File(dataDir, (i++) + name);

                Files.copy(fi.openStream(), file.toPath());

                BuntataDatasource ds = dao.get(id);
                ds.setIcon(file.getName());
                dao.updateIcon(ds);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        throw new ResourceException(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE);
    }
}

From source file:ca.nrc.cadc.rest.SyncInput.java

private void processMultiPart(FileItemIterator itemIterator)
        throws FileUploadException, IOException, ResourceNotFoundException {
    while (itemIterator.hasNext()) {
        FileItemStream item = itemIterator.next();
        String name = item.getFieldName();
        InputStream stream = item.openStream();
        if (item.isFormField())
            processParameter(name, new String[] { Streams.asString(stream) });
        else//from   w  ww  .ja  va2 s . c  om
            processStream(name, item.getContentType(), stream);
    }
}

From source file:com.priocept.jcr.server.UploadServlet.java

private void processFiles(HttpServletRequest request, HttpServletResponse response) {
    HashMap<String, String> args = new HashMap<String, String>();
    try {/*from   w  w  w  .ja  v a 2 s  .  co  m*/
        if (log.isDebugEnabled())
            log.debug(request.getParameterMap());
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        // pick up parameters first and note actual FileItem
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            if (item.isFormField()) {
                args.put(name, Streams.asString(item.openStream()));
            } else {
                args.put("contentType", item.getContentType());
                String fileName = item.getName();
                int slash = fileName.lastIndexOf("/");
                if (slash < 0)
                    slash = fileName.lastIndexOf("\\");
                if (slash > 0)
                    fileName = fileName.substring(slash + 1);
                args.put("fileName", fileName);

                if (log.isDebugEnabled())
                    log.debug(args);

                InputStream in = null;
                try {
                    in = item.openStream();
                    writeToFile(request.getSession().getId() + "/" + fileName, in, true,
                            request.getSession().getServletContext().getRealPath("/"));
                } catch (Exception e) {
                    //                  e.printStackTrace();
                    log.error("Fail to upload " + fileName);

                    response.setContentType("text/html");
                    response.setHeader("Pragma", "No-cache");
                    response.setDateHeader("Expires", 0);
                    response.setHeader("Cache-Control", "no-cache");
                    PrintWriter out = response.getWriter();
                    out.println("<html>");
                    out.println("<body>");
                    out.println("<script type=\"text/javascript\">");
                    out.println("if (parent.uploadFailed) parent.uploadFailed('"
                            + e.getLocalizedMessage().replaceAll("\'|\"", "") + "');");
                    out.println("</script>");
                    out.println("</body>");
                    out.println("</html>");
                    out.flush();
                    return;
                } finally {
                    if (in != null)
                        try {
                            in.close();
                        } catch (Exception e) {
                        }
                }

            }
        }
        response.setContentType("text/html");
        response.setHeader("Pragma", "No-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<body>");
        out.println("<script type=\"text/javascript\">");
        out.println("if (parent.uploadComplete) parent.uploadComplete('" + args.get("fileName") + "');");
        out.println("</script>");
        out.println("</body>");
        out.println("</html>");
        out.flush();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:com.jythonui.server.upload.UpLoadFile.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ServletFileUpload upload = new ServletFileUpload();

    IAddNewBlob addB = SHolder.getAddBlob();

    PrintWriter out = response.getWriter();
    boolean first = true;
    try {/*  w  ww  .  java  2 s . c  om*/
        FileItemIterator iter = upload.getItemIterator(request);

        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            // only uploaded files
            if (item.isFormField())
                continue;

            String fName = item.getName();
            // nothing uploaded
            if (CUtil.EmptyS(fName))
                continue;
            InputStream stream = item.openStream();
            // may be set initial size not default
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte[] buffer = new byte[8192];
            int len;
            while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
                bout.write(buffer, 0, len);
            }
            bout.close();
            // store blob content
            String bkey = addB.addNewBlob(ICommonConsts.BLOBUPLOAD_REALM, ICommonConsts.BLOBUPLOAD_KEY,
                    bout.toByteArray());
            if (!first)
                out.print(',');
            first = false;
            out.print(ICommonConsts.BLOBUPLOAD_REALM);
            out.print(':');
            out.print(bkey);
            out.print(':');
            out.print(fName);
        } // while

    } catch (Exception e) {
        out.print(ICommonConsts.UPLOADFILEERROR);
        IGetLogMess iLog = SHolder.getM();
        String mess = iLog.getMess(IErrorCode.ERRORCODE77, ILogMess.ERRORWHILEUPLOADING);
        log.log(Level.SEVERE, mess, e);
    }
    out.close();

}

From source file:com.github.cxt.Myjersey.jerseycore.FileResource.java

@Path("upload2")
@POST//w  w  w . ja v  a 2s.  com
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public String uploadFile(@Context HttpServletRequest request) throws IOException {
    //??,httpclent?
    System.out.println(request.getCharacterEncoding());
    ServletFileUpload upload = new ServletFileUpload();
    upload.setHeaderEncoding(CHARSET);
    try {
        FileItemIterator fileIterator = upload.getItemIterator(request);
        while (fileIterator.hasNext()) {
            FileItemStream item = fileIterator.next();
            InputStream is = item.openStream();
            try {
                if (!item.isFormField()) {
                    String fileName = item.getName();
                    if (fileName == null || fileName.trim().equals("")) {
                        continue;
                    }
                    String name = Calendar.getInstance().getTimeInMillis() + fileName;
                    String path = request.getServletContext().getRealPath("/");
                    path += File.separator + "data" + File.separator + name;
                    File file = new File(path);
                    FileUtils.copyInputStreamToFile(is, file);
                } else {
                    System.out.println(Streams.asString(is, CHARSET));
                }
            } finally {
                if (null != is) {
                    try {
                        is.close();
                    } catch (IOException ignore) {
                    }
                }
            }
        }
        return "{\"success\": true}";
    } catch (IOException | FileUploadException e) {
        return "{\"success\": false}";
    }
}

From source file:com.googlecode.npackdweb.RepUploadAction.java

@Override
public Page perform(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    List<String> messages = new ArrayList<String>();

    Found f = null;//from  ww  w  .  j  a  v a  2  s  .  c om
    String tag = "unknown";
    boolean overwrite = false;
    if (ServletFileUpload.isMultipartContent(req)) {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iterator;
        try {
            iterator = upload.getItemIterator(req);
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                InputStream stream = item.openStream();

                try {
                    if (item.isFormField()) {
                        if (item.getFieldName().equals("tag")) {
                            BufferedReader r = new BufferedReader(new InputStreamReader(stream));
                            tag = r.readLine();
                        } else if (item.getFieldName().equals("overwrite")) {
                            overwrite = true;
                        }
                    } else {
                        f = process(stream);
                    }
                } finally {
                    stream.close();
                }
            }
        } catch (FileUploadException e) {
            throw (IOException) new IOException(e.getMessage()).initCause(e);
        }
    } else {
        tag = req.getParameter("tag");
        String rep = req.getParameter("repository");
        overwrite = req.getParameter("overwrite") != null;
        f = process(new ByteArrayInputStream(rep.getBytes("UTF-8")));
    }

    if (f != null) {
        boolean isAdmin = NWUtils.isAdminLoggedIn();

        for (PackageVersion pv : f.pvs) {
            pv.tags.add(tag);
        }

        Objectify ofy = DefaultServlet.getObjectify();
        List<Key<?>> keys = new ArrayList<Key<?>>();
        for (License lic : f.lics) {
            keys.add(lic.createKey());
        }
        for (PackageVersion pv : f.pvs) {
            keys.add(pv.createKey());
        }
        for (Package p : f.ps) {
            keys.add(p.createKey());
        }

        Map<Key<Object>, Object> existing = ofy.get(keys);

        Stats stats = new Stats();
        Iterator<PackageVersion> it = f.pvs.iterator();
        while (it.hasNext()) {
            PackageVersion pv = it.next();
            PackageVersion found = (PackageVersion) existing.get(pv.createKey());
            if (found != null) {
                stats.pvExisting++;
                if (!overwrite)
                    it.remove();
            }
        }

        Iterator<License> itLic = f.lics.iterator();
        while (itLic.hasNext()) {
            License pv = itLic.next();
            License found = (License) existing.get(pv.createKey());
            if (found != null) {
                stats.licExisting++;
                if (!overwrite)
                    itLic.remove();
            }
        }

        Iterator<Package> itP = f.ps.iterator();
        while (itP.hasNext()) {
            Package p = itP.next();
            Package found = (Package) existing.get(p.createKey());
            if (found != null) {
                stats.pExisting++;
                if (!overwrite)
                    itP.remove();
            }
        }

        for (PackageVersion pv : f.pvs) {
            Package p = ofy.find(new Key<Package>(Package.class, pv.package_));
            if (p != null && !p.isCurrentUserPermittedToModify())
                messages.add("You do not have permission to modify this package: " + pv.package_);
        }

        for (Package p : f.ps) {
            Package p_ = ofy.find(new Key<Package>(Package.class, p.name));
            if (p_ != null && !p_.isCurrentUserPermittedToModify())
                messages.add("You do not have permission to modify this package: " + p.name);
        }

        if (f.lics.size() > 0) {
            if (isAdmin)
                ofy.put(f.lics);
            else
                messages.add("Only an administrator can change licenses");
        }

        ofy.put(f.pvs);

        for (Package p : f.ps) {
            NWUtils.savePackage(ofy, p, true);
        }

        if (overwrite) {
            stats.pOverwritten = stats.pExisting;
            stats.pvOverwritten = stats.pvExisting;
            stats.licOverwritten = stats.licExisting;
            stats.pAppended = f.ps.size() - stats.pOverwritten;
            stats.pvAppended = f.pvs.size() - stats.pvOverwritten;
            stats.licAppended = f.lics.size() - stats.licOverwritten;
        } else {
            stats.pAppended = f.ps.size();
            stats.pvAppended = f.pvs.size();
            stats.licAppended = f.lics.size();
        }
        messages.add(stats.pOverwritten + " packages overwritten, " + stats.pvOverwritten
                + " package versions overwritten, " + stats.licOverwritten + " licenses overwritten, "
                + stats.pAppended + " packages appended, " + stats.pvAppended + " package versions appended, "
                + stats.licAppended + " licenses appended");
    } else {
        messages.add("No data found");
    }

    return new MessagePage(messages);
}

From source file:com.github.thorqin.webapi.FileManager.java

public List<FileInfo> saveUploadFiles(HttpServletRequest request, int maxSize)
        throws ServletException, IOException, FileUploadException {
    List<FileInfo> uploadList = new LinkedList<>();
    request.setCharacterEncoding("utf-8");
    ServletFileUpload upload = new ServletFileUpload();
    upload.setHeaderEncoding("UTF-8");

    if (!ServletFileUpload.isMultipartContent(request)) {
        return uploadList;
    }//w ww.ja va 2  s  .  com
    upload.setSizeMax(maxSize);
    FileItemIterator iter;
    iter = upload.getItemIterator(request);
    while (iter.hasNext()) {
        FileItemStream item = iter.next();
        try (InputStream stream = item.openStream()) {
            if (!item.isFormField()) {
                FileInfo info = new FileInfo();
                info.setFileName(item.getName());
                if (getFileMIME(info.getExtName()) == null) {
                    logger.log(Level.WARNING, "Upload file's MIME type isn't permitted.");
                    continue;
                }
                info = store(stream, info.fileName);
                uploadList.add(info);
            }
        }
    }
    return uploadList;
}

From source file:de.mpg.imeji.presentation.upload.UploadServlet.java

/**
 * Download the file on the disk in a tmp file
 *
 * @param req/* www. j av a 2  s.co m*/
 * @return
 * @throws FileUploadException
 * @throws IOException
 */
private UploadItem doUpload(HttpServletRequest req) {
    try {
        final ServletFileUpload upload = new ServletFileUpload();
        final FileItemIterator iter = upload.getItemIterator(req);
        UploadItem uploadItem = new UploadItem();
        while (iter.hasNext()) {
            final FileItemStream fis = iter.next();
            if (!fis.isFormField()) {
                uploadItem.setFilename(fis.getName());
                final File tmp = TempFileUtil.createTempFile("upload", null);
                StorageUtils.writeInOut(fis.openStream(), new FileOutputStream(tmp), true);
                uploadItem.setFile(tmp);
            } else {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                StorageUtils.writeInOut(fis.openStream(), out, true);
                uploadItem.getParams().put(fis.getFieldName(), out.toString("UTF-8"));
            }
        }
        return uploadItem;
    } catch (final Exception e) {
        LOGGER.error("Error file upload", e);
    }
    return new UploadItem();
}