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

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

Introduction

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

Prototype

String getFieldName();

Source Link

Document

Returns the name of the field in the multipart form corresponding to this file item.

Usage

From source file:com.niconico.mylasta.direction.sponsor.NiconicoMultipartRequestHandler.java

protected void showFormFieldParameter(FileItem item) {
    if (logger.isDebugEnabled()) {
        logger.debug("[param] {}={}", item.getFieldName(), item.getString());
    }// w w w .j  ava  2 s  . c  o m
}

From source file:com.agapsys.web.toolkit.services.UploadService.java

/**
 * Process a request to receive files.//from   ww w. j  a  va 2 s.c o  m
 * 
 * @param req HTTP request.
 * @param resp HTTP response.
 * @param persistReceivedFiles indicates if received files should be persisted.
 * @param onFormFieldListener listener called when a form field is received.
 * @throws IllegalArgumentException if given request if not multipart/form-data.
 * @return a list of received file by given request.
 */
public List<ReceivedFile> receiveFiles(HttpServletRequest req, HttpServletResponse resp,
        boolean persistReceivedFiles, OnFormFieldListener onFormFieldListener) throws IllegalArgumentException {
    __int();

    if (persistReceivedFiles && resp == null)
        throw new IllegalArgumentException("In order to persist information, response cannot be null");

    if (!ServletFileUpload.isMultipartContent(req))
        throw new IllegalArgumentException("Request is not multipart/form-data");

    try {
        List<ReceivedFile> recvFiles = new LinkedList<>();

        List<FileItem> fileItems = uploadServlet.parseRequest(req);

        for (FileItem fi : fileItems) {
            if (fi.isFormField()) {
                if (onFormFieldListener != null)
                    onFormFieldListener.onFormField(fi.getFieldName(), fi.getString(getFieldEncoding()));
            } else {
                boolean acceptRequest = getAllowedContentTypes().equals("*");

                if (!acceptRequest) {
                    String[] acceptedContentTypes = getAllowedContentTypes().split(Pattern.quote(","));
                    for (String acceptedContentType : acceptedContentTypes) {
                        if (fi.getContentType().equals(acceptedContentType.trim())) {
                            acceptRequest = true;
                            break;
                        }
                    }
                }

                if (!acceptRequest)
                    throw new IllegalArgumentException("Unsupported content-type: " + fi.getContentType());

                File tmpFile = ((DiskFileItem) fi).getStoreLocation();
                String filename = fi.getName();
                ReceivedFile recvFile = new ReceivedFile(tmpFile, filename);
                recvFiles.add(recvFile);
            }
        }

        if (persistReceivedFiles) {
            List<ReceivedFile> sessionRecvFiles = getSessionFiles(req, resp);
            sessionRecvFiles.addAll(recvFiles);
            persistSessionFiles(req, resp, sessionRecvFiles);
        }

        return recvFiles;

    } catch (FileUploadException ex) {
        if (ex instanceof FileUploadBase.SizeLimitExceededException)
            throw new IllegalArgumentException("Size limit exceeded");
        else
            throw new RuntimeException(ex);
    } catch (UnsupportedEncodingException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.krawler.esp.servlets.deskeramob_V1.java

public static String createProject(Connection conn, HttpServletRequest request, String companyid,
        String subdomain, String userid) throws ServiceException {
    String status = "";
    DiskFileUpload fu = new DiskFileUpload();
    java.util.List fileItems = null;
    PreparedStatement pstmt = null;
    String imageName = "";
    try {//  w  w  w.j  a  v  a2s . co m
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        throw ServiceException.FAILURE("Admin.createProject", e);
    }

    java.util.HashMap arrParam = new java.util.HashMap();
    java.util.Iterator k = null;
    for (k = fileItems.iterator(); k.hasNext();) {
        FileItem fi1 = (FileItem) k.next();
        arrParam.put(fi1.getFieldName(), fi1.getString());
    }
    try {
        pstmt = conn
                .prepareStatement("select count(projectid) from project where companyid =? AND archived = 0");
        pstmt.setString(1, companyid);
        ResultSet rs = pstmt.executeQuery();
        int noProjects = 0;
        int maxProjects = 0;
        if (rs.next()) {
            noProjects = rs.getInt(1);
        }
        pstmt = conn.prepareStatement("select maxprojects from company where companyid =?");
        pstmt.setString(1, companyid);
        rs = pstmt.executeQuery();
        if (rs.next()) {
            maxProjects = rs.getInt(1);
        }
        if (noProjects == maxProjects) {
            return "The maximum limit for projects for this company has already reached";
        }
    } catch (SQLException e) {
        throw ServiceException.FAILURE("ProfileHandler.getPersonalInfo", e);
    }
    try {
        String projectid = UUID.randomUUID().toString();
        String projName = StringUtil.serverHTMLStripper(arrParam.get("projectname").toString()
                .replaceAll("[^\\w|\\s|'|\\-|\\[|\\]|\\(|\\)]", "").trim());
        String nickName = AdminServlet.makeNickName(conn, projName, 1);
        if (StringUtil.isNullOrEmpty(projName)) {
            status = "failure";
        } else {
            String qry = "INSERT INTO project (projectid,projectname,description,image,companyid, nickname) VALUES (?,?,?,?,?,?)";
            pstmt = conn.prepareStatement(qry);
            pstmt.setString(1, projectid);
            pstmt.setString(2, projName);
            pstmt.setString(3, arrParam.get("aboutproject").toString());
            pstmt.setString(4, imageName);
            pstmt.setString(5, companyid);
            pstmt.setString(6, nickName);
            int df = pstmt.executeUpdate();
            if (df != 0) {
                pstmt = conn.prepareStatement(
                        "INSERT INTO projectmembers (projectid, userid, status, inuseflag, planpermission) "
                                + "VALUES (?, ?, ?, ?, ?)");
                pstmt.setString(1, projectid);
                pstmt.setString(2, userid);
                pstmt.setInt(3, 4);
                pstmt.setBoolean(4, true);
                pstmt.setInt(5, 0);
                pstmt.executeUpdate();
            }
            //                        /DbUtil.executeUpdate(conn,qry,new Object[] { projectid,projName,arrParam.get("aboutproject"), imageName,companyid, nickName});
            if (arrParam.get("image").toString().length() != 0) {
                genericFileUpload uploader = new genericFileUpload();
                uploader.doPost(fileItems, projectid, StorageHandler.GetProfileImgStorePath());
                if (uploader.isUploaded()) {
                    pstmt = null;
                    //                                        DbUtil.executeUpdate(conn,
                    //                                                        "update project set image=? where projectid = ?",
                    //                                                        new Object[] {
                    //                                                                        ProfileImageServlet.ImgBasePath + projectid
                    //                                                                                        + uploader.getExt(), projectid });

                    pstmt = conn.prepareStatement("update project set image=? where projectid = ?");
                    pstmt.setString(1,
                            ProfileImageServlet.ImgBasePath + projectid + "_200" + uploader.getExt());
                    pstmt.setString(2, projectid);
                    pstmt.executeUpdate();
                    imageName = projectid + uploader.getExt();
                }
            }
            com.krawler.esp.handlers.Forum.setStatusProject(conn, userid, projectid, 4, 0, "", subdomain);
            status = "success";
            AdminServlet.setDefaultWorkWeek(conn, projectid);
            conn.commit();
        }
    } catch (ConfigurationException e) {
        status = "failure";
        throw ServiceException.FAILURE("Admin.createProject", e);
    } catch (SQLException e) {
        status = "failure";
        throw ServiceException.FAILURE("Admin.createProject", e);
    }
    return status;
}

From source file:net.sf.ginp.GinpServlet.java

/**
*  Extract Command Parameter NAmes and Values from the HTTP Request.
*
*@param  req  HTTP Request./*from   w  ww .ja v  a 2s .c o m*/
*@return      A vector of Command Parameters.
*/
final Vector extractParameters(final HttpServletRequest req) {
    Vector params = new Vector();
    Enumeration names = req.getParameterNames();

    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        params.add(new CommandParameter(name, req.getParameter(name)));
        log.debug("new CommandParameter(" + name + ", " + req.getParameter(name) + ")");
    }

    ServletRequestContext reqContext = new ServletRequestContext(req);

    if (FileUpload.isMultipartContent(reqContext)) {
        try {
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload();

            // Set upload parameters
            //upload.setSizeThreshold(yourMaxMemorySize);
            //upload.setSizeMax(yourMaxRequestSize);
            //upload.setRepositoryPath(yourTempDirectory);
            // Parse the request
            List items = upload.parseRequest(req);
            Iterator iter = items.iterator();

            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (item.isFormField()) {
                    params.add(new CommandParameter(item.getFieldName(), item.getString()));
                } else {
                    CommandParameter fileParam = new CommandParameter(item.getFieldName(), item.getName());

                    fileParam.setObject(item.getInputStream());

                    params.add(fileParam);
                }
            }
        } catch (Exception ex) {
            log.error("extract parameters error getting input stream" + " from file upload", ex);
        }
    }

    return params;
}

From source file:com.edgenius.wiki.webapp.servlet.UploadServlet.java

@SuppressWarnings("unchecked")
protected void doService(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if ("GET".equalsIgnoreCase(request.getMethod())) {
        //just render blank page for upload
        String pageUuid = request.getParameter("puuid");
        String spaceUname = request.getParameter("uname");
        String draft = request.getParameter("draft");

        request.setAttribute("pageUuid", pageUuid);
        request.setAttribute("spaceUname", spaceUname);
        request.setAttribute("draft", NumberUtils.toInt(draft, PageType.NONE_DRAFT.value()));

        request.getRequestDispatcher("/WEB-INF/pages/upload.jsp").forward(request, response);

        return;//from   w ww .  j  a va 2  s  .c  om
    }

    //post - upload

    //      if(WikiUtil.getUser().isAnonymous()){
    //      //anonymous can not allow to upload any files

    PageService pageService = getPageService();

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

    List<FileNode> files = new ArrayList<FileNode>();
    String pageUuid = null, spaceUname = null;
    try {
        int status = PageType.NONE_DRAFT.value();
        // index->filename
        Map<String, FileItem> fileMap = new HashMap<String, FileItem>();
        Map<String, String> descMap = new HashMap<String, String>();
        // index->index
        Map<String, String> indexMap = new HashMap<String, String>();

        //offline submission, filename put into hidden variable rather than <input type="file> tag
        Map<String, String> filenameMap = new HashMap<String, String>();
        //TODO: offline submission, version also upload together with file, this give a change to do failure tolerance check:
        //if version is same with online save, then it is OK, if greater, means it maybe duplicated upload, if less, unpexected case
        Map<String, String> versionMap = new HashMap<String, String>();

        Map<String, Boolean> bulkMap = new HashMap<String, Boolean>();

        Map<String, Boolean> sharedMap = new HashMap<String, Boolean>();
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) {
            String name = item.getFieldName();
            if (StringUtils.equals(name, "spaceUname")) {
                spaceUname = item.getString(Constants.UTF8);
            } else if (StringUtils.equals(name, "pageUuid")) {
                pageUuid = item.getString();
            } else if (name.startsWith("draft")) {
                // check this upload is from "click save button" or "auto upload in draft status"
                status = Integer.parseInt(item.getString());
            } else if (name.startsWith("file")) {
                fileMap.put(name.substring(4), item);
                indexMap.put(name.substring(4), name.substring(4));
            } else if (name.startsWith("desc")) {
                descMap.put(name.substring(4), item.getString(Constants.UTF8));
            } else if (name.startsWith("shar")) {
                sharedMap.put(name.substring(4), Boolean.parseBoolean(item.getString()));
            } else if (name.startsWith("name")) {
                filenameMap.put(name.substring(4), item.getString());
            } else if (name.startsWith("vers")) {
                versionMap.put(name.substring(4), item.getString());
            } else if (name.startsWith("bulk")) {
                bulkMap.put(name.substring(4), BooleanUtils.toBoolean(item.getString()));
            }
        }
        if (StringUtils.isBlank(pageUuid)) {
            log.error("Attachment can not be load because of page does not save successfully.");
            throw new PageException("Attachment can not be load because of page does not save successfully.");
        }

        List<FileNode> bulkFiles = new ArrayList<FileNode>();
        String username = request.getRemoteUser();
        // put file/desc pair into final Map
        for (String id : fileMap.keySet()) {
            FileItem item = fileMap.get(id);
            if (item == null || item.getInputStream() == null || item.getSize() <= 0) {
                log.warn("Empty upload item:" + (item != null ? item.getName() : ""));
                continue;
            }
            FileNode node = new FileNode();
            node.setComment(descMap.get(id));
            node.setShared(sharedMap.get(id) == null ? false : sharedMap.get(id));
            node.setFile(item.getInputStream());
            String filename = item.getName();
            if (StringUtils.isBlank(filename)) {
                //this could be offline submission, get name from map
                filename = filenameMap.get(id);
            }
            node.setFilename(FileUtil.getFileName(filename));
            node.setContentType(item.getContentType());
            node.setIndex(indexMap.get(id));
            node.setType(RepositoryService.TYPE_ATTACHMENT);
            node.setIdentifier(pageUuid);
            node.setCreateor(username);
            node.setStatus(status);
            node.setSize(item.getSize());
            node.setBulkZip(bulkMap.get(id) == null ? false : bulkMap.get(id));

            files.add(node);

            if (node.isBulkZip())
                bulkFiles.add(node);
        }
        if (spaceUname != null && pageUuid != null && files.size() > 0) {
            files = pageService.uploadAttachments(spaceUname, pageUuid, files, false);

            //only save non-draft uploaded attachment
            if (status == 0) {
                try {
                    getActivityLog().logAttachmentUploaded(spaceUname,
                            pageService.getCurrentPageByUuid(pageUuid).getTitle(), WikiUtil.getUser(), files);
                } catch (Exception e) {
                    log.warn("Activity log save error for attachment upload", e);
                }
            }
            //as bulk files won't in return list in PageService.uploadAttachments(), here need 
            //append to all return list, but only for client side "uploading panel" clean purpose
            files.addAll(bulkFiles);
            //TODO: if version come in together, then do check
            //            if(versionMap.size() > 0){
            //               for (FileNode node: files) {
            //                  
            //               }
            //            }
        }

    } catch (RepositoryQuotaException e) {
        FileNode att = new FileNode();
        att.setError(getMessageService().getMessage("err.quota.exhaust"));
        files = Arrays.asList(att);
    } catch (AuthenticationException e) {
        String redir = ((RedirectResponseWrapper) response).getRedirect();
        if (redir == null)
            redir = WikiConstants.URL_LOGIN;
        log.info("Send Authentication redirect URL " + redir);

        FileNode att = new FileNode();
        att.setError(getMessageService().getMessage("err.authentication.required"));
        files = Arrays.asList(att);

    } catch (AccessDeniedException e) {
        String redir = ((RedirectResponseWrapper) response).getRedirect();
        if (redir == null)
            redir = WikiConstants.URL_ACCESS_DENIED;
        log.info("Send AccessDenied redirect URL " + redir);

        FileNode att = new FileNode();
        att.setError(getMessageService().getMessage("err.access.denied"));
        files = Arrays.asList(att);

    } catch (Exception e) {
        // FileUploadException,RepositoryException
        log.error("File upload failed ", e);
        FileNode att = new FileNode();
        att.setError(getMessageService().getMessage("err.upload"));
        files = Arrays.asList(att);
    }

    try {
        String json = FileNode.toAttachmentsJson(files, spaceUname, WikiUtil.getUser(), getMessageService(),
                getUserReadingService());

        //TODO: does not compress request in Gzip, refer to 
        //http://www.google.com/codesearch?hl=en&q=+RemoteServiceServlet+show:PAbNFg2Qpdo:akEoB_bGF1c:4aNSrXYgYQ4&sa=N&cd=1&ct=rc&cs_p=https://ssl.shinobun.org/svn/repos/trunk&cs_f=proprietary/gwt/gwt-user/src/main/java/com/google/gwt/user/server/rpc/RemoteServiceServlet.java#first
        byte[] reply = json.getBytes(Constants.UTF8);
        response.setContentLength(reply.length);
        response.setContentType("text/plain; charset=utf-8");
        response.getOutputStream().write(reply);
    } catch (IOException e) {
        log.error(e.toString(), e);
    }
}

From source file:com.sun.faban.harness.webclient.RunUploader.java

/**
 * Post method to upload the run./*from   www . j  a v  a  2s  .c o m*/
 * @param request The servlet request
 * @param response The servlet response
 * @throws ServletException If the servlet fails
 * @throws IOException If there is an I/O error
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String host = null;
    String key = null;
    boolean origin = false; // Whether the upload is to the original
    // run requestor. If so, key is needed.

    DiskFileUpload fu = new DiskFileUpload();
    // No maximum size
    fu.setSizeMax(-1);
    // maximum size that will be stored in memory
    fu.setSizeThreshold(4096);
    // the location for saving data that is larger than getSizeThreshold()
    fu.setRepositoryPath(Config.TMP_DIR);

    List fileItems = null;
    try {
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        throw new ServletException(e);
    }
    // assume we know there are two files. The first file is a small
    // text file, the second is unknown and is written to a file on
    // the server
    for (Iterator i = fileItems.iterator(); i.hasNext();) {
        FileItem item = (FileItem) i.next();
        String fieldName = item.getFieldName();
        if (item.isFormField()) {
            if ("host".equals(fieldName)) {
                host = item.getString();
            } else if ("key".equals(fieldName)) {
                key = item.getString();
            } else if ("origin".equals(fieldName)) {
                String value = item.getString();
                origin = Boolean.parseBoolean(value);
            }
            continue;
        }

        if (host == null) {
            logger.warning("Host not received on upload request!");
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            break;
        }

        // The host, origin, key info must be here before we receive
        // any file.
        if (origin) {
            if (Config.daemonMode != Config.DaemonModes.POLLEE) {
                logger.warning("Origin upload requested. Not pollee!");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                break;
            }
            if (key == null) {
                logger.warning("Origin upload requested. No key!");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                break;
            }
            if (!RunRetriever.authenticate(host, key)) {
                logger.warning("Origin upload requested. " + "Host/key mismatch: " + host + '/' + key + "!");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                break;
            }
        }

        if (!"jarfile".equals(fieldName)) // ignore
            continue;

        String fileName = item.getName();

        if (fileName == null) // We don't process files without names
            continue;

        // Now, this name may have a path attached, dependent on the
        // source browser. We need to cover all possible clients...
        char[] pathSeparators = { '/', '\\' };
        // Well, if there is another separator we did not account for,
        // just add it above.

        for (int j = 0; j < pathSeparators.length; j++) {
            int idx = fileName.lastIndexOf(pathSeparators[j]);
            if (idx != -1) {
                fileName = fileName.substring(idx + 1);
                break;
            }
        }

        // Ignore all non-jarfiles.
        if (!fileName.toLowerCase().endsWith(".jar"))
            continue;
        File uploadFile = new File(Config.TMP_DIR, host + '.' + fileName);
        try {
            item.write(uploadFile);
        } catch (Exception e) {
            throw new ServletException(e);
        }
        File runTmp = unjarTmp(uploadFile);

        String runId = null;

        if (origin) {
            // Change origin file to know where this run came from.
            File metaInf = new File(runTmp, "META-INF");
            File originFile = new File(metaInf, "origin");
            if (!originFile.exists()) {
                logger.warning("Origin upload requested. Origin file" + "does not exist!");
                response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Origin file does not exist!");
                break;
            }

            RunId origRun;
            try {
                origRun = new RunId(readStringFromFile(originFile).trim());
            } catch (IndexOutOfBoundsException e) {
                response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
                        "Origin file error. " + e.getMessage());
                break;
            }

            runId = origRun.getBenchName() + '.' + origRun.getRunSeq();
            String localHost = origRun.getHostName();
            if (!localHost.equals(Config.FABAN_HOST)) {
                logger.warning("Origin upload requested. Origin host " + localHost
                        + " does not match this host " + Config.FABAN_HOST + '!');
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                break;
            }
            writeStringToFile(runTmp.getName(), originFile);
        } else {
            runId = runTmp.getName();
        }

        if (recursiveCopy(runTmp, new File(Config.OUT_DIR, runId))) {
            uploadFile.delete();
            recursiveDelete(runTmp);
        } else {
            logger.warning("Origin upload requested. Copy error!");
            response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE);
            break;
        }

        response.setStatus(HttpServletResponse.SC_CREATED);
        break;
    }
}

From source file:com.scooterframework.web.controller.ScooterRequestFilter.java

protected String requestInfo(boolean skipStatic, HttpServletRequest request) {
    String method = getRequestMethod(request);
    String requestPath = getRequestPath(request);
    String requestPathKey = RequestInfo.generateRequestKey(requestPath, method);
    String s = requestPathKey;//from  w ww .  ja  v a  2s.  c  o m
    String queryString = request.getQueryString();
    if (queryString != null)
        s += "?" + queryString;

    CurrentThreadCacheClient.cacheHttpMethod(method);
    CurrentThreadCacheClient.cacheRequestPath(requestPath);
    CurrentThreadCacheClient.cacheRequestPathKey(requestPathKey);

    if (skipStatic)
        return s;

    //request header
    Properties headers = new Properties();
    Enumeration<?> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = (String) headerNames.nextElement();
        String value = request.getHeader(name);
        if (value != null)
            headers.setProperty(name, value);
    }
    CurrentThreadCache.set(Constants.REQUEST_HEADER, headers);

    if (isLocalRequest(request)) {
        CurrentThreadCache.set(Constants.LOCAL_REQUEST, Constants.VALUE_FOR_LOCAL_REQUEST);
    }

    if (isFileUploadRequest(request)) {
        CurrentThreadCache.set(Constants.FILE_UPLOAD_REQUEST, Constants.VALUE_FOR_FILE_UPLOAD_REQUEST);

        try {
            List<FileItem> files = new ArrayList<FileItem>();
            ServletFileUpload fileUpload = EnvConfig.getInstance().getServletFileUpload();
            List<?> items = fileUpload.parseRequest(request);
            for (Object fi : items) {
                FileItem item = (FileItem) fi;
                if (item.isFormField()) {
                    ActionControl.storeToRequest(item.getFieldName(), item.getString());
                } else if (!item.isFormField() && !"".equals(item.getName())) {
                    files.add(item);
                }
            }
            CurrentThreadCache.set(Constants.FILE_UPLOAD_REQUEST_FILES, files);
        } catch (Exception ex) {
            CurrentThreadCacheClient.storeError(new FileUploadException(ex));
        }
    }

    return s;
}

From source file:Controller.Publicacion.java

private String uploadFile(HttpServletRequest request) {
    String imageName = "", textfield = "";
    String archivourl = "C:\\xampp\\htdocs\\RedSocial\\web\\files";
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(5000 * 1024);
    factory.setRepository(new File(archivourl));
    ServletFileUpload upload = new ServletFileUpload(factory);

    try {/*ww w  .  java2  s  .com*/
        List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        String inputName = null;
        for (FileItem item : multiparts) {
            if (!item.isFormField()) {
                String name = new File(item.getName()).getName();
                item.write(new File(archivourl + File.separator + name));
                imageName = name;
            }
            if (item.isFormField()) {
                inputName = (String) item.getFieldName();
                if (inputName.equalsIgnoreCase("cont")) {
                    textfield = (String) item.getString();
                    imageName = textfield;
                }
            }
        }

    } catch (Exception e) {

    }
    return imageName;
}

From source file:cn.itcast.fredck.FCKeditor.connector.ConnectorServlet.java

/**
 * Manage the Post requests (FileUpload).<br>
 *
 * The servlet accepts commands sent in the following format:<br>
 * connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<br><br>
 * It store the file (renaming it in case a file with the same name exists) and then return an HTML file
 * with a javascript command in it./*from ww  w. j a  v a2s.  com*/
 *
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (debug)
        System.out.println("--- BEGIN DOPOST ---");

    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    String currentPath = baseDir + typeStr + currentFolderStr;
    String currentDirPath = getServletContext().getRealPath(currentPath);

    if (debug)
        System.out.println(currentDirPath);

    String retVal = "0";
    String newName = "";

    if (!commandStr.equals("FileUpload"))
        retVal = "203";
    else {
        DiskFileUpload upload = new DiskFileUpload();
        try {
            List items = upload.parseRequest(request);

            Map fields = new HashMap();

            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField())
                    fields.put(item.getFieldName(), item.getString());
                else
                    fields.put(item.getFieldName(), item);
            }
            FileItem uplFile = (FileItem) fields.get("NewFile");
            String fileNameLong = uplFile.getName();
            fileNameLong = fileNameLong.replace('\\', '/');
            String[] pathParts = fileNameLong.split("/");
            String fileName = pathParts[pathParts.length - 1];

            String nameWithoutExt = getNameWithoutExtension(fileName);
            String ext = getExtension(fileName);
            File pathToSave = new File(currentDirPath, fileName);
            int counter = 1;
            while (pathToSave.exists()) {
                newName = nameWithoutExt + "(" + counter + ")" + "." + ext;
                retVal = "201";
                pathToSave = new File(currentDirPath, newName);
                counter++;
            }
            uplFile.write(pathToSave);
        } catch (Exception ex) {
            retVal = "203";
        }

    }

    out.println("<script type=\"text/javascript\">");
    out.println("window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + newName + "');");
    out.println("</script>");
    out.flush();
    out.close();

    if (debug)
        System.out.println("--- END DOPOST ---");

}

From source file:at.gv.egiz.pdfas.web.servlets.VerifyServlet.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)//  w  ww  .  j av  a  2 s . co  m
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    logger.info("Post verify request");

    String errorUrl = PdfAsParameterExtractor.getInvokeErrorURL(request);
    PdfAsHelper.setErrorURL(request, response, errorUrl);

    StatisticEvent statisticEvent = new StatisticEvent();
    statisticEvent.setStartNow();
    statisticEvent.setSource(Source.WEB);
    statisticEvent.setOperation(Operation.VERIFY);
    statisticEvent.setUserAgent(UserAgentFilter.getUserAgent());

    try {
        byte[] filecontent = null;

        // checks if the request actually contains upload file
        if (!ServletFileUpload.isMultipartContent(request)) {
            // No Uploaded data!
            if (PdfAsParameterExtractor.getPdfUrl(request) != null) {
                doGet(request, response);
                return;
            } else {
                throw new PdfAsWebException("No Signature data defined!");
            }
        } else {
            // configures upload settings
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(THRESHOLD_SIZE);
            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(MAX_FILE_SIZE);
            upload.setSizeMax(MAX_REQUEST_SIZE);

            // constructs the directory path to store upload file
            String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
            // creates the directory if it does not exist
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }

            List<?> formItems = upload.parseRequest(request);
            logger.debug(formItems.size() + " Items in form data");
            if (formItems.size() < 1) {
                // No Uploaded data!
                // Try do get
                // No Uploaded data!
                if (PdfAsParameterExtractor.getPdfUrl(request) != null) {
                    doGet(request, response);
                    return;
                } else {
                    throw new PdfAsWebException("No Signature data defined!");
                }
            } else {
                for (int i = 0; i < formItems.size(); i++) {
                    Object obj = formItems.get(i);
                    if (obj instanceof FileItem) {
                        FileItem item = (FileItem) obj;
                        if (item.getFieldName().equals(UPLOAD_PDF_DATA)) {
                            filecontent = item.get();
                            try {
                                File f = new File(item.getName());
                                String name = f.getName();
                                logger.debug("Got upload: " + item.getName());
                                if (name != null) {
                                    if (!(name.endsWith(".pdf") || name.endsWith(".PDF"))) {
                                        name += ".pdf";
                                    }

                                    logger.debug("Setting Filename in session: " + name);
                                    PdfAsHelper.setPDFFileName(request, name);
                                }
                            } catch (Throwable e) {
                                logger.warn("In resolving filename", e);
                            }
                            if (filecontent.length < 10) {
                                filecontent = null;
                            } else {
                                logger.debug("Found pdf Data! Size: " + filecontent.length);
                            }
                        } else {
                            request.setAttribute(item.getFieldName(), item.getString());
                            logger.debug("Setting " + item.getFieldName() + " = " + item.getString());
                        }
                    } else {
                        logger.debug(obj.getClass().getName() + " - " + obj.toString());
                    }
                }
            }
        }

        if (filecontent == null) {
            if (PdfAsParameterExtractor.getPdfUrl(request) != null) {
                filecontent = RemotePDFFetcher.fetchPdfFile(PdfAsParameterExtractor.getPdfUrl(request));
            }
        }

        if (filecontent == null) {
            Object sourceObj = request.getAttribute("source");
            if (sourceObj != null) {
                String source = sourceObj.toString();
                if (source.equals("internal")) {
                    request.setAttribute("FILEERR", true);
                    request.getRequestDispatcher("index.jsp").forward(request, response);

                    statisticEvent.setStatus(Status.ERROR);
                    statisticEvent.setException(new Exception("No file uploaded"));
                    statisticEvent.setEndNow();
                    statisticEvent.setTimestampNow();
                    StatisticFrontend.getInstance().storeEvent(statisticEvent);
                    statisticEvent.setLogged(true);

                    return;
                }
            }
            throw new PdfAsException("No Signature data available");
        }

        doVerify(request, response, filecontent, statisticEvent);
    } catch (Throwable e) {

        statisticEvent.setStatus(Status.ERROR);
        statisticEvent.setException(e);
        if (e instanceof PDFASError) {
            statisticEvent.setErrorCode(((PDFASError) e).getCode());
        }
        statisticEvent.setEndNow();
        statisticEvent.setTimestampNow();
        StatisticFrontend.getInstance().storeEvent(statisticEvent);
        statisticEvent.setLogged(true);

        logger.warn("Generic Error: ", e);
        PdfAsHelper.setSessionException(request, response, e.getMessage(), e);
        PdfAsHelper.gotoError(getServletContext(), request, response);
    }
}