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

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

Introduction

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

Prototype

String getContentType();

Source Link

Document

Returns the content type passed by the browser or null if not defined.

Usage

From source file:org.xsystem.sql2.http.impl.HttpHelper.java

public static Map formUploadJson(HttpServletRequest request)
        throws FileUploadException, UnsupportedEncodingException {
    Map ret = new HashMap();
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");
    List items = upload.parseRequest(request);
    Iterator iterator = items.iterator();

    while (iterator.hasNext()) {
        FileItem item = (FileItem) iterator.next();
        String paramName = item.getFieldName();

        if (item.isFormField()) {
            String svalue = item.getString("UTF-8");
            Gson gson = RestApiTemplate.gsonBuilder.create();
            Object jsonContext = gson.fromJson(svalue, Object.class);
            ret.put(paramName, jsonContext);
        } else {//  w  w  w . j av a 2  s  .c om

            FileTransfer fileTransfer = new FileTransfer();
            String fileName = item.getName();
            String contentType = item.getContentType();
            byte[] data = item.get();
            fileTransfer.setFileName(fileName);
            String ft = Auxilary.getFileExtention(fileName);
            fileTransfer.setFileType(ft);
            fileTransfer.setContentType(contentType);
            fileTransfer.setData(data);
            ret.put(paramName, fileTransfer);
        }
    }
    return ret;
}

From source file:org.zoxweb.server.http.servlet.HTTPServletUtil.java

@SuppressWarnings("unchecked")
public static HTTPRequestAttributes extractRequestAttributes(HttpServletRequest req, boolean readParameters)
        throws IOException {
    HTTPRequestAttributes ret = null;/*from  w ww.j a  v  a2 s  . co  m*/

    DiskFileItemFactory dfif = null;
    List<FileItem> items = null;
    // check if the request is of multipart type
    List<GetNameValue<String>> headers = extractRequestHeaders(req);
    List<GetNameValue<String>> params = new ArrayList<GetNameValue<String>>();
    List<FileInfoStreamSource> streamList = new ArrayList<FileInfoStreamSource>();

    /*
     *    Retrieve path info if it exists. If the pathInfo starts or ends with a "/", the "/" is removed
     *    and value is trimmed.
     */
    String pathInfo = req.getPathInfo();
    //   Removing the first "/" in pathInfo.
    pathInfo = SharedStringUtil.trimOrNull(SharedStringUtil.valueAfterLeftToken(pathInfo, "/"));
    //   Removing the last "/" in pathInfo.
    if (pathInfo != null) {
        if (pathInfo.endsWith("/")) {
            pathInfo = SharedStringUtil.trimOrNull(pathInfo.substring(0, pathInfo.length() - 1));
        }
    }

    if (ServletFileUpload.isMultipartContent(req)) {

        dfif = new DiskFileItemFactory();
        try {
            ServletFileUpload upload = new ServletFileUpload(dfif);
            upload.setHeaderEncoding(SharedStringUtil.UTF_8);
            items = upload.parseRequest(req);
        } catch (FileUploadException e) {
            throw new IOException("Upload problem:" + e);
        }
        for (FileItem fi : items) {
            if (fi.isFormField()) {
                String name = fi.getFieldName();
                String value = fi.getString();
                params.add(new NVPair(name, value));

            } else {
                String content = fi.getContentType();
                InputStream is = fi.getInputStream();
                String filename = fi.getName();
                FileInfoDAO fid = new FileInfoDAO();
                fid.setName(filename);
                fid.setCreationTime(System.currentTimeMillis());
                fid.setContentType(content);
                fid.setLength(fi.getSize());

                FileInfoStreamSource fiss = new FileInfoStreamSource(fid, is);
                streamList.add(fiss);
            }
        }

        ret = new HTTPRequestAttributes(req.getRequestURI(), pathInfo, req.getContentType(), true, headers,
                params, streamList);
    } else {
        if (readParameters) {
            params = (List<GetNameValue<String>>) SharedUtil.toNVPairs(req.getParameterMap());
        }

        ret = new HTTPRequestAttributes(req.getRequestURI(), pathInfo, req.getContentType(), false, headers,
                params, streamList, new HTTPRequestStringContentDecoder(req));
    }

    return ret;
}

From source file:petascope.wcps.server.servlet.WcpsServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.debug("WCPS: invoked with POST");
    OutputStream webOut = null;//from   www.  ja  va 2s . c  om

    meta.clearCache();
    Wcps wcps;

    try {
        meta.ensureConnection();
        wcps = new Wcps(new File(getServletContext().getRealPath(WCPS_PROCESS_COVERAGE_XSD)), meta);
    } catch (Exception e) {
        throw new ServletException("Error initializing WCPS", e);
    }

    try {
        String xmlRequest = null;
        response.setHeader("Access-Control-Allow-Origin", "*");

        if (ServletFileUpload.isMultipartContent(request)) {
            @SuppressWarnings("unchecked")
            Iterator<FileItem> fileItems = (Iterator<FileItem>) (new ServletFileUpload(
                    new DiskFileItemFactory())).parseRequest(request).iterator();

            if (!fileItems.hasNext()) {
                throw new IOException("Multipart POST request contains no parts");
            }

            FileItem fileItem = fileItems.next();

            if (fileItems.hasNext()) {
                throw new IOException("Multipart POST request contains too many parts");
            }

            if (!fileItem.isFormField() && fileItem.getContentType().equals("text/xml")) {
                xmlRequest = fileItem.getString();
            }

            if (xmlRequest == null) {
                log.warn("WCPS: no XML file was uploaded within multipart POST request");
                printUsage(response);
                return;
            }

            log.debug("WCPS: received XML via a multipart POST request");
        } else {
            String xml = request.getParameter(WcpsConstants.MSG_XML);
            String query = request.getParameter(WcpsConstants.MSG_QUERY);

            if (xml != null) {
                log.debug("WCPS: received XML via a 'xml' parameter in a POST request");
                xmlRequest = xml;
            } else if (query != null) {
                log.debug(
                        "WCPS: received the following  query via a 'query' " + "parameter in a POST request:");
                log.debug(query);

                xmlRequest = RasUtil.abstractWCPStoXML(query);
            } else {
                log.debug("WCPS: no request was received");
                printUsage(response);
                return;
            }
        }

        log.debug("-------------------------------------------------------");
        log.debug("Converting to rasql");
        ProcessCoveragesRequest processCoverageRequest = wcps.pcPrepare(ConfigManager.RASDAMAN_URL,
                ConfigManager.RASDAMAN_DATABASE, IOUtils.toInputStream(xmlRequest));
        log.debug("-------------------------------------------------------");

        String query = processCoverageRequest.getRasqlQuery();
        String mime = processCoverageRequest.getMime();

        response.setContentType(mime);
        webOut = response.getOutputStream();

        /* Alireza
        Object res = processCoverageRequest.execute();
        if (res instanceof RasQueryResult){
        log.debug("executing request");
        log.debug("[" + mime + "] " + query);
                
        for (String s : ((RasQueryResult) res).getScalars()) {
            webOut.write(s.getBytes());
        }
        for (byte[] bs : ((RasQueryResult) res).getMdds()) {
            webOut.write(bs);
        }
                
        } else if (res instanceof String){
        webOut.write(out.getBytes());
        }
        */

        if (processCoverageRequest.isRasqlQuery()) {
            log.debug("executing request");
            log.debug("[" + mime + "] " + query);

            RasQueryResult res = new RasQueryResult(processCoverageRequest.execute());
            for (String s : res.getScalars()) {
                webOut.write(s.getBytes());
            }
            for (byte[] bs : res.getMdds()) {
                webOut.write(bs);
            }
            // Execute the query ... (?)
        } else if (processCoverageRequest.isPostGISQuery()) {
            PostgisQueryResult res = new PostgisQueryResult(processCoverageRequest.execute());
            webOut.write(res.toCSV(res.getValues()).getBytes());

        } else {
            log.debug("metadata result, no rasql to execute");
            webOut.write(query.getBytes());
        }
        log.debug("WCPS: done");
    } catch (WCPSException e) {
        response.setStatus(e.getExceptionCode().getHttpErrorCode());
        printError(response, "WCPS Error: " + e.getMessage(), e);
    } catch (SecoreException e) {
        response.setStatus(e.getExceptionCode().getHttpErrorCode());
        printError(response, "SECORE Error: " + e.getMessage(), e);
    } catch (Exception e) {
        response.setStatus(ExceptionCode.DEFAULT_EXIT_CODE);
        printError(response, "Error: " + e.getMessage(), e);
    } finally {
        if (webOut != null) {
            try {
                webOut.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:play.data.parsing.ApacheMultipartParser.java

public Map<String, String[]> parse(InputStream body) {
    Map<String, String[]> result = new HashMap<String, String[]>();
    try {/*  w  w  w  .j  a v  a2  s .  c  o  m*/
        FileItemIteratorImpl iter = new FileItemIteratorImpl(body,
                Request.current().headers.get("content-type").value(), Request.current().encoding);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            FileItem fileItem = new AutoFileItem(item);
            try {
                Streams.copy(item.openStream(), fileItem.getOutputStream(), true);
            } catch (FileUploadIOException e) {
                throw (FileUploadException) e.getCause();
            } catch (IOException e) {
                throw new IOFileUploadException(
                        "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage(), e);
            }
            if (fileItem.isFormField()) {
                // must resolve encoding
                String _encoding = Request.current().encoding; // this is our default
                String _contentType = fileItem.getContentType();
                if (_contentType != null) {
                    HTTP.ContentTypeWithEncoding contentTypeEncoding = HTTP.parseContentType(_contentType);
                    if (contentTypeEncoding.encoding != null) {
                        _encoding = contentTypeEncoding.encoding;
                    }
                }

                putMapEntry(result, fileItem.getFieldName(), fileItem.getString(_encoding));
            } else {
                @SuppressWarnings("unchecked")
                List<Upload> uploads = (List<Upload>) Request.current().args.get("__UPLOADS");
                if (uploads == null) {
                    uploads = new ArrayList<Upload>();
                    Request.current().args.put("__UPLOADS", uploads);
                }
                try {
                    uploads.add(new FileUpload(fileItem));
                } catch (Exception e) {
                    // GAE does not support it, we try in memory
                    uploads.add(new MemoryUpload(fileItem));
                }
                putMapEntry(result, fileItem.getFieldName(), fileItem.getFieldName());
            }
        }
    } catch (FileUploadIOException e) {
        Logger.debug(e, "error");
        throw new IllegalStateException("Error when handling upload", e);
    } catch (IOException e) {
        Logger.debug(e, "error");
        throw new IllegalStateException("Error when handling upload", e);
    } catch (FileUploadException e) {
        Logger.debug(e, "error");
        throw new IllegalStateException("Error when handling upload", e);
    } catch (Exception e) {
        Logger.debug(e, "error");
        throw new UnexpectedException(e);
    }
    return result;
}

From source file:plugin.upload.action.A.java

@Action
@Route("/action")
public Response.View action(FileItem file, String text, Bean bean) throws IOException {
    if (file != null) {
        AbstractUploadTestCase.contentType = file.getContentType();
        AbstractUploadTestCase.content = file.getString();
        AbstractUploadTestCase.text = text;
        AbstractUploadTestCase.field = bean != null ? bean.field : null;
    }/*from ww w.j  ava 2s .  c  o  m*/
    return A_.index();
}

From source file:plugin.upload.resource.A.java

@Resource
@Route("/resource")
public Response.Status resource(FileItem file, String text, Bean bean) throws IOException {
    if (file != null) {
        AbstractUploadTestCase.contentType = file.getContentType();
        AbstractUploadTestCase.content = file.getString();
        AbstractUploadTestCase.text = text;
        AbstractUploadTestCase.field = bean != null ? bean.field : null;
    }//from w w w. j  a va  2  s. c o m
    return Response.ok();
}

From source file:project.handler.post.ProjectPostHandler.java

/**
     * Parse the import params from the request
     * @param request the http request/*from  w  w  w  . j ava  2  s  . c  o  m*/
     */
void parseImportParams(HttpServletRequest request) throws ProjectException {
    try {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // Parse the request
            List items = upload.parseRequest(request);
            for (int i = 0; i < items.size(); i++) {
                FileItem item = (FileItem) items.get(i);
                if (item.isFormField()) {
                    String fieldName = item.getFieldName();
                    if (fieldName != null) {
                        String contents = item.getString("UTF-8");
                        processField(fieldName, contents);
                    }
                } else if (item.getName().length() > 0) {
                    try {
                        // item.getName retrieves the ORIGINAL file name
                        String type = item.getContentType();
                        if (type != null) {
                            if (type.startsWith("image/")) {
                                InputStream is = item.getInputStream();
                                ByteHolder bh = new ByteHolder();
                                while (is.available() > 0) {
                                    byte[] b = new byte[is.available()];
                                    is.read(b);
                                    bh.append(b);
                                }
                                icon = new ImageFile(item.getName(), item.getContentType(), bh.getData());
                            } else
                                System.out.println("skipping file type" + type);
                        }
                    } catch (Exception e) {
                        throw new ProjectException(e);
                    }
                }
            }
        } else {
            Map tbl = request.getParameterMap();
            Set<String> keys = tbl.keySet();
            Iterator<String> iter = keys.iterator();
            while (iter.hasNext()) {
                String key = iter.next();
                String[] values = (String[]) tbl.get(key);
                for (int i = 0; i < values.length; i++)
                    processField(key, values[i]);
            }
        }
    } catch (Exception e) {
        throw new ProjectException(e);
    }
}

From source file:ru.simplgroupp.rest.api.service.UserSettingsService.java

/**
 *   ?/*from  ww w.  j  a  va2s. c  om*/
 *
 * @param maps - 
 * @param user - 
 * @return - ? 
 * @throws KassaException
 * @throws PeopleException
 */
public List<ErrorData> savePeopleContact(Map<String, Object> maps, Users user)
        throws KassaException, PeopleException, IOException {
    if (!aiService.getCanAdd()) {
        throw new PeopleException("  ");
    }
    List<ErrorData> errors = new ArrayList<>();
    PeopleMain ppl = peopleDAO.getPeopleMain(user.getPeopleMain().getId(),
            Utils.setOf(PeopleMain.Options.INIT_PEOPLE_PERSONAL, PeopleMain.Options.INIT_PEOPLE_MISC,
                    PeopleMain.Options.INIT_SPOUSE, PeopleMain.Options.INIT_PEOPLE_CONTACT));

    String oldPhone = peopleBean.findContactClient(PeopleContact.CONTACT_CELL_PHONE,
            user.getPeopleMain().getId());
    if (StringUtils.isEmpty((String) maps.get("phoneCode"))) {

        if (oldPhone == null) {
            errors.add(
                    new ErrorData("phoneCode", " ? ? ?"));
        }
    } else {
        if (maps.get("phoneHash") != null && !maps.get("phoneHash").equals(
                StaticFuncs.md5("salt" + oldPhone + "supersalt" + maps.get("phoneCode") + "megasalt"))) {
            errors.add(new ErrorData("phoneCode", "  ?? "));
        }
    }

    if (errors.size() > 0) {
        return errors;
    }

    if (maps.get("inn") != null) {
        if (CheckUtils.CheckInn((String) maps.get("inn"))) {
            ppl.setInn((String) maps.get("inn"));
        }
    }
    if (maps.get("snils") != null) {
        if (CheckUtils.CheckSnils((String) maps.get("snils"))) {
            ppl.setSnils((String) maps.get("snils"));
        }
    }
    PeoplePersonal personal = ppl.getPeoplePersonalActive();
    PeopleMisc misc = ppl.getPeopleMiscActive();
    if (maps.get("car") != null) {
        misc.setCar((Boolean) maps.get("car"));
    }

    if (maps.get("hasDriverDoc") != null) {
        misc.setDriverLicense((Boolean) maps.get("hasDriverDoc"));
    }

    peopleBean.changePeopleData(personal, misc, null, ppl, Partner.CLIENT, new Date());

    if (maps.get("passportDocFile") != null
            && this.cacheFCR.hasUploadedFile((String) maps.get("passportDocFile"))) {
        FileItem passportFile = this.cacheFCR.getUploadedFile((String) maps.get("passportDocFile"));

        this.docsDAO.saveDocumentPage(null, user.getPeopleMain().getId(), DocumentMedia.SCAN_TYPE_PASP, null, 1,
                passportFile.getContentType(), passportFile.getName(),
                IOUtils.toByteArray(passportFile.getInputStream()));

    }

    if (maps.get("innDocFile") != null && this.cacheFCR.hasUploadedFile((String) maps.get("innDocFile"))) {
        FileItem innFile = this.cacheFCR.getUploadedFile((String) maps.get("innDocFile"));

        this.docsDAO.saveDocumentPage(null, user.getPeopleMain().getId(), DocumentMedia.SCAN_TYPE_INN, null, 1,
                innFile.getContentType(), innFile.getName(), IOUtils.toByteArray(innFile.getInputStream()));

    }

    if (maps.get("snilsFile") != null && this.cacheFCR.hasUploadedFile((String) maps.get("snilsFile"))) {
        FileItem snilsFile = this.cacheFCR.getUploadedFile((String) maps.get("snilsFile"));

        this.docsDAO.saveDocumentPage(null, user.getPeopleMain().getId(), DocumentMedia.SCAN_TYPE_SNILS, null,
                1, snilsFile.getContentType(), snilsFile.getName(),
                IOUtils.toByteArray(snilsFile.getInputStream()));

    }

    if (maps.get("autoCardFile") != null && this.cacheFCR.hasUploadedFile((String) maps.get("autoCardFile"))) {
        FileItem driverFile = this.cacheFCR.getUploadedFile((String) maps.get("autoCardFile"));

        this.docsDAO.saveDocumentPage(null, user.getPeopleMain().getId(), DocumentMedia.SCAN_TYPE_DRIVE, null,
                1, driverFile.getContentType(), driverFile.getName(),
                IOUtils.toByteArray(driverFile.getInputStream()));

    }

    return errors;
}

From source file:ru.simplgroupp.rest.api.service.UserSettingsService.java

/**
 * ??    (, ??, , )//from w  ww .j  a va2 s.  c  o  m
 *
 * @param additionalData 
 * @param user            
 * @return  OK ? ? ,  ? ??
 * @throws KassaException
 * @throws PeopleException
 * @throws IOException
 */
public String saveAdditionalData(AdditionalData additionalData, Users user)
        throws KassaException, PeopleException, IOException {
    if (!aiService.isCanEdit()) {
        throw new PeopleException("  ");
    }

    String error = checkSmsCode(additionalData.getSmsCode());
    if (error != null) {
        throw new PeopleException(error);
    }

    PeopleMain peopleMain = peopleDAO.getPeopleMain(user.getPeopleMain().getId(),
            Utils.setOf(PeopleMain.Options.INIT_PEOPLE_PERSONAL, PeopleMain.Options.INIT_PEOPLE_MISC,
                    PeopleMain.Options.INIT_SPOUSE, PeopleMain.Options.INIT_PEOPLE_CONTACT));

    PeopleMisc misc = peopleMain.getPeopleMiscActive();

    misc.setCar(additionalData.getCar());
    misc.setDriverLicense(additionalData.getDriverLicense());

    //    ?   ??,  
    //   ??  ?'a ?? ?
    boolean hasInnBefore = peopleMain.getInn() != null;
    boolean hasSnilsBefore = peopleMain.getSnils() != null;

    peopleBean.savePeopleMain(peopleMain.getEntity(), additionalData.getInn(), additionalData.getSnils());
    peopleBean.changePeopleData(null, misc, null, peopleMain, Partner.CLIENT, new Date());

    try {
        // ? ?   ??'a ?      ?
        if (!hasInnBefore && peopleMain.getInn() != null) {
            peopleBean.addBonus(peopleMain.getId(), PeopleBonus.BONUS_CODE_INN_ADD, BaseCredit.OPERATION_IN);
        }
        // ? ?   ?'a ?     ?
        if (!hasSnilsBefore && peopleMain.getSnils() != null) {
            peopleBean.addBonus(peopleMain.getId(), PeopleBonus.BONUS_CODE_SNILS_ADD, BaseCredit.OPERATION_IN);
        }
    } catch (PeopleException pe) {
        logger.severe("? ?  ? " + pe);
    }

    if (additionalData.getPassportFile() != null
            && cacheFCR.hasUploadedFile(additionalData.getPassportFile())) {
        FileItem passportFile = cacheFCR.getUploadedFile(additionalData.getPassportFile());

        docsDAO.saveDocumentPage(null, user.getPeopleMain().getId(), DocumentMedia.SCAN_TYPE_PASP, null, 1,
                passportFile.getContentType(), passportFile.getName(),
                IOUtils.toByteArray(passportFile.getInputStream()));
        try {
            peopleBean.addBonus(user.getPeopleMain().getId(), PeopleBonus.BONUS_CODE_DOC_ADD,
                    BaseCredit.OPERATION_IN);
        } catch (PeopleException e) {
            logger.severe("? ?  ? " + e);
        }
    }
    if (additionalData.getPassportRegistrationFile() != null
            && cacheFCR.hasUploadedFile(additionalData.getPassportRegistrationFile())) {
        FileItem passportRegistrationFile = cacheFCR
                .getUploadedFile(additionalData.getPassportRegistrationFile());

        docsDAO.saveDocumentPage(null, user.getPeopleMain().getId(), DocumentMedia.SCAN_TYPE_PASP, null, 2,
                passportRegistrationFile.getContentType(), passportRegistrationFile.getName(),
                IOUtils.toByteArray(passportRegistrationFile.getInputStream()));
        try {
            peopleBean.addBonus(user.getPeopleMain().getId(), PeopleBonus.BONUS_CODE_DOC_ADD,
                    BaseCredit.OPERATION_IN);
        } catch (PeopleException e) {
            logger.severe("? ?  ? " + e);
        }
    }

    if (additionalData.getInnFile() != null && cacheFCR.hasUploadedFile(additionalData.getInnFile())) {
        FileItem innFile = cacheFCR.getUploadedFile(additionalData.getInnFile());

        docsDAO.saveDocumentPage(null, user.getPeopleMain().getId(), DocumentMedia.SCAN_TYPE_INN, null, 1,
                innFile.getContentType(), innFile.getName(), IOUtils.toByteArray(innFile.getInputStream()));
        try {
            peopleBean.addBonus(user.getPeopleMain().getId(), PeopleBonus.BONUS_CODE_DOC_ADD,
                    BaseCredit.OPERATION_IN);
        } catch (PeopleException e) {
            logger.severe("? ?  ? " + e);
        }
    }

    if (additionalData.getSnilsFile() != null && cacheFCR.hasUploadedFile(additionalData.getSnilsFile())) {
        FileItem snilsFile = this.cacheFCR.getUploadedFile(additionalData.getSnilsFile());

        docsDAO.saveDocumentPage(null, user.getPeopleMain().getId(), DocumentMedia.SCAN_TYPE_SNILS, null, 1,
                snilsFile.getContentType(), snilsFile.getName(),
                IOUtils.toByteArray(snilsFile.getInputStream()));
        try {
            peopleBean.addBonus(user.getPeopleMain().getId(), PeopleBonus.BONUS_CODE_DOC_ADD,
                    BaseCredit.OPERATION_IN);
        } catch (PeopleException e) {
            logger.severe("? ?  ? " + e);
        }
    }

    if (additionalData.getDriverLicenceFile() != null
            && cacheFCR.hasUploadedFile(additionalData.getDriverLicenceFile())) {
        FileItem driverFile = cacheFCR.getUploadedFile(additionalData.getDriverLicenceFile());

        docsDAO.saveDocumentPage(null, user.getPeopleMain().getId(), DocumentMedia.SCAN_TYPE_DRIVE, null, 1,
                driverFile.getContentType(), driverFile.getName(),
                IOUtils.toByteArray(driverFile.getInputStream()));
        try {
            peopleBean.addBonus(user.getPeopleMain().getId(), PeopleBonus.BONUS_CODE_DOC_ADD,
                    BaseCredit.OPERATION_IN);
        } catch (PeopleException e) {
            logger.severe("? ?  ? " + e);
        }
    }

    return "OK";
}

From source file:rva.administrator.ASRepFileUpload.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {
    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    if (!isMultipart) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
        return;/*from  w  w  w  .j  a va  2  s.  c  om*/
    }
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File("c:\\temp"));
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);
    try {
        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);
        // Process the uploaded file items
        Iterator i = fileItems.iterator();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                } else {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                }
                fi.write(file);
                String upfile = filePath + fileName;
                ReadExcels.readExcels(upfile);
                out.println("<html>");
                out.println("<body>");
                HttpSession session = request.getSession();
                response.sendRedirect("fileuploading.jsp");
                session.setAttribute("filepathas", upfile);
                // RequestDispatcher rd=request.getRequestDispatcher("fileuploading.jsp");
                // rd.include(request, response);
                //out.println("Uploaded Filename:" +upfile+ "<br>");
                out.println("</body>");
                out.println("</html>");
            }
        }
        out.println("</body>");
        out.println("</html>");
    } catch (Exception ex) {
        System.out.println(ex);
    }
}