Example usage for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload

Introduction

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

Prototype

public ServletFileUpload() 

Source Link

Document

Constructs an uninitialised instance of this class.

Usage

From source file:com.runwaysdk.web.WebFileUploadServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    ClientRequestIF clientRequest = (ClientRequestIF) req.getAttribute(ClientConstants.CLIENTREQUEST);

    // capture the session id
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);

    if (!isMultipart) {
        // TODO Change exception type
        String msg = "The HTTP Request must contain multipart content.";
        throw new RuntimeException(msg);
    }/* www . j  a v a2s  .co m*/

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload();

    upload.setFileItemFactory(factory);

    try {
        // Parse the request
        FileItemIterator iter = upload.getItemIterator(req);

        String fileName = null;
        String extension = null;
        InputStream stream = null;
        String uploadPath = null;
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            InputStream input = item.openStream();
            if (item.isFormField() && item.getFieldName().equals(WEB_FILE_UPLOAD_PATH_FIELD_NAME)) {
                uploadPath = Streams.asString(input);
            } else if (!item.isFormField()) {
                String fullName = item.getName();
                int extensionInd = fullName.lastIndexOf(".");
                fileName = fullName.substring(0, extensionInd);
                extension = fullName.substring(extensionInd + 1);
                stream = input;
            }
        }

        if (stream != null) {
            clientRequest.newFile(uploadPath, fileName, extension, stream);
        }
    } catch (FileUploadException e) {
        throw new FileWriteExceptionDTO(e.getLocalizedMessage());
    }
}

From source file:edu.caltech.ipac.firefly.server.servlets.AnyFileUpload.java

protected void processRequest(HttpServletRequest req, HttpServletResponse res) throws Exception {

    String dest = req.getParameter(DEST_PARAM);
    String preload = req.getParameter(PRELOAD_PARAM);
    String overrideCacheKey = req.getParameter(CACHE_KEY);
    String fileType = req.getParameter(FILE_TYPE);

    if (!ServletFileUpload.isMultipartContent(req)) {
        sendReturnMsg(res, 400, "Is not a Multipart request. Request rejected.", "");
    }/* w  ww  . j  a va  2 s.c  o m*/
    StopWatch.getInstance().start("Upload File");

    ServletFileUpload upload = new ServletFileUpload();
    FileItemIterator iter = upload.getItemIterator(req);
    while (iter.hasNext()) {
        FileItemStream item = iter.next();

        if (!item.isFormField()) {
            String fileName = item.getName();
            InputStream inStream = new BufferedInputStream(item.openStream(),
                    IpacTableUtil.FILE_IO_BUFFER_SIZE);
            String ext = resolveExt(fileName);
            FileType fType = resolveType(fileType, ext, item.getContentType());
            File destDir = resolveDestDir(dest, fType);
            boolean doPreload = resolvePreload(preload, fType);

            File uf = File.createTempFile("upload_", ext, destDir);
            String rPathInfo = ServerContext.replaceWithPrefix(uf);

            UploadFileInfo fi = new UploadFileInfo(rPathInfo, uf, fileName, item.getContentType());
            String fileCacheKey = overrideCacheKey != null ? overrideCacheKey : rPathInfo;
            UserCache.getInstance().put(new StringKey(fileCacheKey), fi);

            if (doPreload && fType == FileType.FITS) {
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(uf),
                        IpacTableUtil.FILE_IO_BUFFER_SIZE);
                TeeInputStream tee = new TeeInputStream(inStream, bos);
                try {
                    final Fits fits = new Fits(tee);
                    FitsRead[] frAry = FitsRead.createFitsReadArray(fits);
                    FitsCacher.addFitsReadToCache(uf, frAry);
                } finally {
                    FileUtil.silentClose(bos);
                    FileUtil.silentClose(tee);
                }
            } else {
                FileUtil.writeToFile(inStream, uf);
            }
            sendReturnMsg(res, 200, null, fileCacheKey);
            Counters.getInstance().increment(Counters.Category.Upload, fi.getContentType());
            return;
        }
    }
    StopWatch.getInstance().printLog("Upload File");
}

From source file:com.example.getstarted.basicactions.CreateBookServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    assert ServletFileUpload.isMultipartContent(req);
    CloudStorageHelper storageHelper = (CloudStorageHelper) getServletContext().getAttribute("storageHelper");

    String newImageUrl = null;/*from  w ww  .j  av  a  2s .com*/
    Map<String, String> params = new HashMap<String, String>();
    try {
        FileItemIterator iter = new ServletFileUpload().getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), Streams.asString(item.openStream()));
            } else if (!Strings.isNullOrEmpty(item.getName())) {
                newImageUrl = storageHelper.uploadFile(item,
                        getServletContext().getInitParameter("bookshelf.bucket"));
            }
        }
    } catch (FileUploadException e) {
        throw new IOException(e);
    }

    String createdByString = "";
    String createdByIdString = "";
    HttpSession session = req.getSession();
    if (session.getAttribute("userEmail") != null) { // Does the user have a logged in session?
        createdByString = (String) session.getAttribute("userEmail");
        createdByIdString = (String) session.getAttribute("userId");
    }

    Book book = new Book.Builder().author(params.get("author")).description(params.get("description"))
            .publishedDate(params.get("publishedDate")).title(params.get("title"))
            .imageUrl(null == newImageUrl ? params.get("imageUrl") : newImageUrl).createdBy(createdByString)
            .createdById(createdByIdString).build();

    BookDao dao = (BookDao) this.getServletContext().getAttribute("dao");
    try {
        Long id = dao.createBook(book);
        logger.log(Level.INFO, "Created book {0}", book);
        resp.sendRedirect("/read?id=" + id.toString()); // read what we just wrote
    } catch (Exception e) {
        throw new ServletException("Error creating book", e);
    }
}

From source file:com.example.getstarted.basicactions.UpdateBookServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    BookDao dao = (BookDao) this.getServletContext().getAttribute("dao");

    assert ServletFileUpload.isMultipartContent(req);
    CloudStorageHelper storageHelper = (CloudStorageHelper) getServletContext().getAttribute("storageHelper");

    String newImageUrl = null;//ww  w .  ja va2s  . com
    Map<String, String> params = new HashMap<String, String>();
    try {
        FileItemIterator iter = new ServletFileUpload().getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), Streams.asString(item.openStream()));
            } else if (!Strings.isNullOrEmpty(item.getName())) {
                newImageUrl = storageHelper.uploadFile(item,
                        getServletContext().getInitParameter("bookshelf.bucket"));
            }
        }
    } catch (FileUploadException e) {
        throw new IOException(e);
    }

    try {
        Book oldBook = dao.readBook(Long.decode(params.get("id")));

        Book book = new Book.Builder().author(params.get("author")).description(params.get("description"))
                .publishedDate(params.get("publishedDate")).title(params.get("title"))
                .imageUrl(null == newImageUrl ? params.get("imageUrl") : newImageUrl)
                .id(Long.decode(params.get("id"))).createdBy(oldBook.getCreatedBy())
                .createdById(oldBook.getCreatedById()).build();

        dao.updateBook(book);
        resp.sendRedirect("/read?id=" + params.get("id"));
    } catch (Exception e) {
        throw new ServletException("Error updating book", e);
    }
}

From source file:com.google.phonenumbers.PhoneNumberParserServlet.java

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String phoneNumber = null;//from  w w  w .  j  a  v a 2  s  .co m
    String defaultCountry = null;
    String languageCode = "en"; // Default languageCode to English if nothing is entered.
    String regionCode = "";
    String fileContents = null;
    ServletFileUpload upload = new ServletFileUpload();
    upload.setSizeMax(50000);
    try {
        FileItemIterator iterator = upload.getItemIterator(req);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream in = item.openStream();
            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                if (fieldName.equals("phoneNumber")) {
                    phoneNumber = Streams.asString(in, "UTF-8");
                } else if (fieldName.equals("defaultCountry")) {
                    defaultCountry = Streams.asString(in).toUpperCase();
                } else if (fieldName.equals("languageCode")) {
                    String languageEntered = Streams.asString(in).toLowerCase();
                    if (languageEntered.length() > 0) {
                        languageCode = languageEntered;
                    }
                } else if (fieldName.equals("regionCode")) {
                    regionCode = Streams.asString(in).toUpperCase();
                }
            } else {
                try {
                    fileContents = IOUtils.toString(in);
                } finally {
                    IOUtils.closeQuietly(in);
                }
            }
        }
    } catch (FileUploadException e1) {
        e1.printStackTrace();
    }

    StringBuilder output;
    if (fileContents.length() == 0) {
        output = getOutputForSingleNumber(phoneNumber, defaultCountry, languageCode, regionCode);
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().println("<html><head>");
        resp.getWriter()
                .println("<link type=\"text/css\" rel=\"stylesheet\" href=\"/stylesheets/main.css\" />");
        resp.getWriter().println("</head>");
        resp.getWriter().println("<body>");
        resp.getWriter().println("Phone Number entered: " + phoneNumber + "<br>");
        resp.getWriter().println("defaultCountry entered: " + defaultCountry + "<br>");
        resp.getWriter().println("Language entered: " + languageCode
                + (regionCode.length() == 0 ? "" : " (" + regionCode + ")" + "<br>"));
    } else {
        output = getOutputForFile(defaultCountry, fileContents);
        resp.setContentType("text/html");
    }
    resp.getWriter().println(output);
    resp.getWriter().println("</body></html>");
}

From source file:edu.isi.wings.portal.servlets.HandleUpload.java

/**
 * Handle an HTTP POST request from Plupload.
 *///  w w  w.  j  a va 2s  . c  o m
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    Config config = new Config(request);
    if (!config.checkDomain(request, response))
        return;

    Domain dom = config.getDomain();

    String name = null;
    String id = null;
    String storageDir = dom.getDomainDirectory() + "/";
    int chunk = 0;
    int chunks = 0;
    boolean isComponent = false;

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter;
        try {
            iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                try {
                    InputStream input = item.openStream();
                    if (item.isFormField()) {
                        String fieldName = item.getFieldName();
                        String value = Streams.asString(input);
                        if ("name".equals(fieldName))
                            name = value.replaceAll("[^\\w\\.\\-_]+", "_");
                        else if ("id".equals(fieldName))
                            id = value;
                        else if ("type".equals(fieldName)) {
                            if ("data".equals(value))
                                storageDir += dom.getDataLibrary().getStorageDirectory();
                            else if ("component".equals(value)) {
                                storageDir += dom.getConcreteComponentLibrary().getStorageDirectory();
                                isComponent = true;
                            } else {
                                storageDir = System.getProperty("java.io.tmpdir");
                            }
                        } else if ("chunk".equals(fieldName))
                            chunk = Integer.parseInt(value);
                        else if ("chunks".equals(fieldName))
                            chunks = Integer.parseInt(value);
                    } else if (name != null) {
                        File storageDirFile = new File(storageDir);
                        if (!storageDirFile.exists())
                            storageDirFile.mkdirs();
                        File uploadFile = new File(storageDirFile.getPath() + "/" + name + ".part");
                        saveUploadFile(input, uploadFile, chunk);
                    }
                } catch (Exception e) {
                    this.printError(out, e.getMessage());
                    e.printStackTrace();
                }
            }
        } catch (FileUploadException e1) {
            this.printError(out, e1.getMessage());
            e1.printStackTrace();
        }
    } else {
        this.printError(out, "Not multipart data");
    }

    if (chunks == 0 || chunk == chunks - 1) {
        // Done upload
        File partUpload = new File(storageDir + File.separator + name + ".part");
        File finalUpload = new File(storageDir + File.separator + name);
        partUpload.renameTo(finalUpload);

        String mime = new Tika().detect(finalUpload);
        if (mime.equals("application/x-sh") || mime.startsWith("text/"))
            FileUtils.writeLines(finalUpload, FileUtils.readLines(finalUpload));

        // Check if this is a zip file and unzip if needed
        String location = finalUpload.getAbsolutePath();
        if (isComponent && mime.equals("application/zip")) {
            String dirname = new URI(id).getFragment();
            location = StorageHandler.unzipFile(finalUpload, dirname, storageDir);
            finalUpload.delete();
        }
        this.printOk(out, location);
    }
}

From source file:com.amalto.core.servlet.UploadFile.java

private void uploadFile(HttpServletRequest req, Writer writer) throws ServletException, IOException {
    // upload file
    if (!ServletFileUpload.isMultipartContent(req)) {
        throw new ServletException("Upload File Error: the request is not multipart!"); //$NON-NLS-1$
    }//from   w  w w.j av  a2 s . c  o m
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();

    // Set upload parameters
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(0);
    upload.setFileItemFactory(factory);
    upload.setSizeMax(-1);

    // Parse the request
    List<FileItem> items;
    try {
        items = upload.parseRequest(req);
    } catch (Exception e) {
        throw new ServletException(e.getMessage(), e);
    }

    // Process the uploaded items
    if (items != null && items.size() > 0) {
        // Only one file
        Iterator<FileItem> iter = items.iterator();
        FileItem item = iter.next();
        if (LOG.isDebugEnabled()) {
            LOG.debug(item.getFieldName());
        }

        File file = null;
        if (!item.isFormField()) {
            try {
                String filename = item.getName();
                if (req.getParameter(PARAMETER_DEPLOY_JOB) != null) {
                    String contextStr = req.getParameter(PARAMETER_CONTEXT);
                    file = writeJobFile(item, filename, contextStr);
                } else if (filename.endsWith(".bar")) { //$NON-NLS-1$
                    file = writeWorkflowFile(item, filename);
                } else {
                    throw new IllegalArgumentException("Unknown deployment for file '" + filename + "'"); //$NON-NLS-1$ //$NON-NLS-2$
                }
            } catch (Exception e) {
                throw new ServletException(e.getMessage(), e);
            }
        } else {
            throw new ServletException("Couldn't process request"); //$NON-NLS-1$);
        }
        String urlRedirect = req.getParameter("urlRedirect"); //$NON-NLS-1$
        if (Boolean.valueOf(urlRedirect)) {
            String redirectUrl = req.getContextPath() + "?mimeFile=" + file.getName(); //$NON-NLS-1$
            writer.write(redirectUrl);
        } else {
            writer.write(file.getAbsolutePath());
        }
    }
    writer.close();
}

From source file:it.polimi.modaclouds.cloudapp.mic.servlet.RegisterServlet.java

private void parseReq(HttpServletRequest req, HttpServletResponse response)
        throws ServletException, IOException {

    try {/* ww w.  ja va2  s. c om*/

        MF mf = MF.getFactory();

        req.setCharacterEncoding("UTF-8");

        ServletFileUpload upload = new ServletFileUpload();

        FileItemIterator iterator = upload.getItemIterator(req);

        HashMap<String, String> map = new HashMap<String, String>();

        while (iterator.hasNext()) {

            FileItemStream item = iterator.next();

            InputStream stream = item.openStream();

            if (item.isFormField()) {

                String field = item.getFieldName();

                String value = Streams.asString(stream);

                map.put(field, value);

                stream.close();

            } else {

                String filename = item.getName();

                String[] extension = filename.split("\\.");

                String mail = map.get("mail");

                if (mail != null) {

                    filename = mail + "_" + String.valueOf(filename.hashCode()) + "."
                            + extension[extension.length - 1];

                } else {

                    filename = String.valueOf(filename.hashCode()) + "." + extension[extension.length - 1];

                }

                map.put("filename", filename);

                byte[] buffer = IOUtils.toByteArray(stream);

                mf.getBlobManagerFactory().createCloudBlobManager().uploadBlob(buffer,

                        filename);

                stream.close();

            }

        }

        String email = map.get("mail");

        String firstName = map.get("firstName");

        String lastName = map.get("lastName");

        String dayS = map.get("day");

        String monthS = map.get("month");

        String yearS = map.get("year");

        String password = map.get("password");

        String filename = map.get("filename");

        String date = yearS + "-" + monthS + "-" + dayS;

        char gender = map.get("gender").charAt(0);

        RequestDispatcher disp;

        Connection c = mf.getSQLService().getConnection();

        String stm = "INSERT INTO UserProfile VALUES('" + email + "', '" + password + "', '" + firstName
                + "', '" + lastName + "', '" + date + "', '" + gender + "', '" + filename + "')";

        Statement statement = c.createStatement();

        statement.executeUpdate(stm);

        statement.close();

        c.close();

        req.getSession(true).setAttribute("actualUser", email);

        req.getSession(true).setAttribute("edit", "false");

        disp = req.getRequestDispatcher("SelectTopic.jsp");

        disp.forward(req, response);

    } catch (UnsupportedEncodingException e) {

        e.printStackTrace();

    } catch (SQLException e) {

        e.printStackTrace();

    } catch (FileUploadException e) {

        e.printStackTrace();

    }

}

From source file:fi.jyu.student.jatahama.onlineinquirytool.server.LoadSaveServlet.java

@Override
public final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {/* w ww  . j  av  a2  s  .  c  o  m*/
        // We always return xhtml in utf-8
        response.setContentType("application/xhtml+xml");
        response.setCharacterEncoding("utf-8");

        // Default filename just in case none is found in form
        String filename = defaultFilename;

        // Commons file upload
        ServletFileUpload upload = new ServletFileUpload();

        // Go through upload items
        FileItemIterator iterator = upload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                // Parse form fields
                String fieldname = item.getFieldName();

                if ("chartFilename".equals(fieldname)) {
                    // Ordering is important in client page! We expect filename BEFORE data. Otherwise filename will be default
                    // See also: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4
                    //   "The parts are sent to the processing agent in the same order the
                    //    corresponding controls appear in the document stream."
                    filename = Streams.asString(stream, "utf-8");
                } else if ("chartDataXML".equals(fieldname)) {
                    log.info("Doing form bounce");
                    String filenameAscii = formSafeAscii(filename);
                    String fileNameUtf = formSafeUtfName(filename);
                    String cdh = "attachment; filename=\"" + filenameAscii + "\"; filename*=utf-8''"
                            + fileNameUtf;
                    response.setHeader("Content-Disposition", cdh);
                    ServletOutputStream out = response.getOutputStream();
                    Streams.copy(stream, out, false);
                    out.flush();
                    // No more processing needed (prevent BOTH form AND upload from happening)
                    return;
                }
            } else {
                // Handle upload
                log.info("Doing file bounce");
                ServletOutputStream out = response.getOutputStream();
                Streams.copy(stream, out, false);
                out.flush();
                // No more processing needed (prevent BOTH form AND upload from happening)
                return;
            }
        }
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
}

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

/**
 * Creates a new {@link DynamicInputImpl}
 * @param request from which to read the request parameters
 *///w  w  w  .j a  v a  2  s .  co m
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();
    }
}