Example usage for org.springframework.web.multipart.commons CommonsMultipartResolver isMultipart

List of usage examples for org.springframework.web.multipart.commons CommonsMultipartResolver isMultipart

Introduction

In this page you can find the example usage for org.springframework.web.multipart.commons CommonsMultipartResolver isMultipart.

Prototype

@Override
    public boolean isMultipart(HttpServletRequest request) 

Source Link

Usage

From source file:org.openxdata.server.servlet.FormOpenServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from  w ww  .jav a 2s . co  m*/
        CommonsMultipartResolver multipartResover = new CommonsMultipartResolver(/*this.getServletContext()*/);
        if (multipartResover.isMultipart(request)) {
            MultipartHttpServletRequest multipartRequest = multipartResover.resolveMultipart(request);
            MultipartFile uploadedFile = multipartRequest.getFile("filecontents");
            if (uploadedFile != null && !uploadedFile.isEmpty())
                request.getSession().setAttribute(KEY_FILE_CONTENTS,
                        IOUtils.toString(uploadedFile.getInputStream(), "UTF-8"));
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:org.openxdata.server.servlet.FormSaveServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from  w w  w .j a  v a 2 s  . c  o m
        String filecontents = null;
        CommonsMultipartResolver multipartResover = new CommonsMultipartResolver(/*this.getServletContext()*/);
        if (multipartResover.isMultipart(request)) {
            MultipartHttpServletRequest multipartRequest = multipartResover.resolveMultipart(request);
            filecontents = multipartRequest.getParameter("filecontents");
            if (filecontents == null || filecontents.trim().length() == 0)
                return;
        }

        String filename = "filename.xml";
        if (request.getParameter("filename") != null) {
            filename = request.getParameter("filename") + ".xml";
            filename = filename.replace(" ", "-");
        }

        HttpSession session = request.getSession();
        session.setAttribute(KEY_FILE_NAME, filename);
        session.setAttribute(KEY_FILE_CONTENTS, filecontents);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:org.openxdata.server.servlet.ImportServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*  w  ww  .j a  v  a  2  s.  c  o m*/
        String importType = request.getParameter("type");
        String filecontents = null;

        CommonsMultipartResolver multipartResover = new CommonsMultipartResolver(/*this.getServletContext()*/);
        if (multipartResover.isMultipart(request)) {
            MultipartHttpServletRequest multipartRequest = multipartResover.resolveMultipart(request);
            MultipartFile uploadedFile = multipartRequest.getFile("filecontents");
            if (uploadedFile != null && !uploadedFile.isEmpty()) {
                filecontents = IOUtils.toString(uploadedFile.getInputStream());
            }
        }

        if (filecontents != null) {
            log.info("Starting import of type: " + importType);

            if (importType.equals("user")) {
                String errors = userService.importUsers(filecontents);
                if (errors != null) {
                    writeErrorsToResponse(errors, response);
                }
            } else {
                log.warn("Unknown import type: " + importType);
            }
        }
    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.getOutputStream().print(ex.getMessage());
    }
}

From source file:io.pivotal.PaasappApplication.java

@RequestMapping("upload")
public String uploadFiles(HttpServletRequest request) throws IllegalStateException, IOException {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
            request.getSession().getServletContext());
    if (multipartResolver.isMultipart(request)) {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        //?multiRequest ??
        Iterator iter = multiRequest.getFileNames();

        while (iter.hasNext()) {
            //??/*w  w  w  .  ja  v a 2  s. c  o  m*/
            MultipartFile file = multiRequest.getFile(iter.next().toString());
            if (file != null) {
                String path = file.getOriginalFilename();
                //
                file.transferTo(new File(path));
            }

        }
    }

    return "/success";
}

From source file:com.qq.tars.web.controller.patch.UploadController.java

@RequestMapping(value = "server/api/upload_patch_package", produces = "application/json")
@ResponseBody/* www. j a va 2 s  . c o  m*/
public ServerPatchView upload(@Application @RequestParam String application,
        @ServerName @RequestParam("module_name") String moduleName, HttpServletRequest request,
        ModelMap modelMap) throws Exception {
    String comment = StringUtils.trimToEmpty(request.getParameter("comment"));
    String uploadTgzBasePath = systemConfigService.getUploadTgzPath();

    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
            request.getSession().getServletContext());
    if (multipartResolver.isMultipart(request)) {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        Iterator<String> it = multiRequest.getFileNames();
        if (it.hasNext()) {
            MultipartFile file = multiRequest.getFile(it.next());

            String originalName = file.getOriginalFilename();
            String extension = FilenameUtils.getExtension(originalName);
            String temporary = uploadTgzBasePath + "/" + UUID.randomUUID() + "." + extension;
            IOUtils.copy(file.getInputStream(), new FileOutputStream(temporary));

            String packageType = "suse";

            // war?
            if (temporary.endsWith(".war")) {
                temporary = patchService.war2tgz(temporary, moduleName);
            }

            // ?
            String updateTgzPath = uploadTgzBasePath + "/" + application + "/" + moduleName;

            // ????
            String uploadTgzName = application + "." + moduleName + "_" + packageType + "_"
                    + System.currentTimeMillis() + ".tgz";

            // ??
            String uploadTgzFullPath = updateTgzPath + "/" + uploadTgzName;

            log.info("temporary path={}, upload path={}", temporary, uploadTgzFullPath);

            File uploadPathDir = new File(updateTgzPath);
            if (!uploadPathDir.exists()) {
                if (!uploadPathDir.mkdirs()) {
                    throw new IOException(
                            String.format("mkdirs error, path=%s", uploadPathDir.getCanonicalPath()));
                }
            }

            FileUtils.moveFile(new File(temporary), new File(uploadTgzFullPath));

            return mapper.map(patchService.addServerPatch(application, moduleName, uploadTgzFullPath, comment),
                    ServerPatchView.class);
        }
    }

    throw new Exception("???");
}

From source file:org.openxdata.server.servlet.MultimediaServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String formId = request.getParameter("formId");
    String xpath = request.getParameter("xpath");

    CommonsMultipartResolver multipartResover = new CommonsMultipartResolver(/*this.getServletContext()*/);
    if (multipartResover.isMultipart(request)) {
        MultipartHttpServletRequest multipartRequest = multipartResover.resolveMultipart(request);
        MultipartFile uploadedFile = multipartRequest.getFile("filecontents");
        if (uploadedFile != null && !uploadedFile.isEmpty()) {
            byte[] postData = uploadedFile.getBytes();
            response.getOutputStream().print(new String(Base64.encodeBase64(postData)));

            setSessionData(request, formId, KEY_MULTIMEDIA_POST_CONTENT_TYPE + getFieldKey(formId, xpath),
                    uploadedFile.getContentType());
            setSessionData(request, formId, KEY_MULTIMEDIA_POST_DATA + getFieldKey(formId, xpath), postData);
        }//w w w. j a  v  a  2 s.  com
    }
}

From source file:com.emaxcore.emaxdata.modules.testdrive.pub.web.TestdriveUploadSignatureController.java

/**
 * ???????//from  ww  w  .  j  ava 2 s  . c o  m
 *
 * @param model
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping(value = "uploadSignature")
@ResponseBody
public String uploadSignature(ModelMap model, HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    if (isDebugLogger) {
        logger.debug(" ??------uploadSignature-------start--------");
    }
    response.setContentType(TestdrivePubConstant.ENCODED);
    Map<?, ?> jsonMap = null;

    // ?
    // ???????
    StringBuilder idcardDriveProtocol = new StringBuilder();

    // ???????
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
            request.getSession().getServletContext());
    if (multipartResolver.isMultipart(request)) {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

        // json
        String jsonDataStr = multiRequest.getParameter(TestdrivePubConstant.VALUE);

        if (Global.isSecretMode()) {
            if (isDebugLogger) {
                logger.debug("app ?---------- Start------{}---------", jsonDataStr);
            }
            AES256EncryptionUtils des = AES256EncryptionUtils.getInstance();
            String jsonData = des.decrypt(jsonDataStr);
            jsonMap = JsonMapper.nonDefaultMapper().fromJson(jsonData, HashMap.class);
        } else {
            jsonMap = JsonMapper.nonDefaultMapper().fromJson(jsonDataStr, HashMap.class);
        }
        if (isDebugLogger) {
            logger.debug("uploadSignature?----------jsonMap---{}---------", jsonMap);
        }

        // ?
        TestDriveApplyInfo testDriveApplyInfo = new TestDriveApplyInfo();

        //??--
        String userFristName = TestdrivePubUtils.readJsonMapValue("fristName", jsonMap);
        if (StringUtils.isBlank(userFristName)) {
            jsonMap = this.saveJson(TestdrivePubConstant.ERROR_STATE, "fristName", "");
            return TestdrivePubUtils.loggerJsonMap(jsonMap);
        }
        testDriveApplyInfo.setFirstName(userFristName);

        //??--
        String userLastName = TestdrivePubUtils.readJsonMapValue("lastName", jsonMap);
        if (StringUtils.isBlank(userLastName)) {
            jsonMap = this.saveJson(TestdrivePubConstant.ERROR_STATE, "lastName", "");
            return TestdrivePubUtils.loggerJsonMap(jsonMap);
        }
        testDriveApplyInfo.setLastName(userLastName);

        //??
        String userName = userFristName + userLastName;
        testDriveApplyInfo.setName(userName);

        //telephone
        String telephone = TestdrivePubUtils.readJsonMapValue("telephone", jsonMap);
        if (StringUtils.isBlank(telephone)) {
            jsonMap = this.saveJson(TestdrivePubConstant.ERROR_STATE, "telephone", "");
            return TestdrivePubUtils.loggerJsonMap(jsonMap);
        }
        testDriveApplyInfo.setMobile(telephone);

        //appellation 
        String appellation = TestdrivePubUtils.readJsonMapValue("appellation", jsonMap);
        if (StringUtils.isBlank(appellation)) {
            jsonMap = this.saveJson(TestdrivePubConstant.ERROR_STATE, "appellation", "");
            return TestdrivePubUtils.loggerJsonMap(jsonMap);
        }
        testDriveApplyInfo.setSex(appellation);

        //motorcycleType 
        String motorcycleType = TestdrivePubUtils.readJsonMapValue("motorcycleType", jsonMap);
        if (StringUtils.isBlank(motorcycleType)) {
            jsonMap = this.saveJson(TestdrivePubConstant.ERROR_STATE, "motorcycleType", "");
            return TestdrivePubUtils.loggerJsonMap(jsonMap);
        }
        testDriveApplyInfo.setVehiclesType(motorcycleType);

        //
        String widthName = TestdrivePubUtils.readJsonMapValue("userName", jsonMap);
        if (StringUtils.isBlank(widthName)) {
            jsonMap = this.saveJson(TestdrivePubConstant.ERROR_STATE, "userName", "");
            return TestdrivePubUtils.loggerJsonMap(jsonMap);
        }
        testDriveApplyInfo.setWidthName(widthName);

        // ?MD5
        String idCarMD5Hash = TestdrivePubUtils.readJsonMapValue("IDCarMD5Hash", jsonMap);
        // MD5
        String driveMD5Hash = TestdrivePubUtils.readJsonMapValue("driveMD5Hash", jsonMap);
        // ????MD5
        String protocolMD5Hash = TestdrivePubUtils.readJsonMapValue("protocolMD5Hash", jsonMap);

        // ???
        String cidNumber = TestdrivePubUtils.readJsonMapValue("IDNumber", jsonMap);
        if (StringUtils.isBlank(cidNumber)) {
            jsonMap = this.saveJson(TestdrivePubConstant.ERROR_STATE, "???", "");
            return TestdrivePubUtils.loggerJsonMap(jsonMap);
        }
        testDriveApplyInfo.setIdNumber(cidNumber);

        // ?D:\apache-tomcat-7.0.47\webapps\benz
        String path = TestdrivePubUtils.getRealPath(request);
        // ????/mnt/sdc1/data/benzsite
        String savePath = Global.getUserfilesBaseDir();
        // ?/userfiles/app/login ??login
        String signaturePicAddressPre = TestdrivePubConstant.APP_USER_FILES_PATH + userName;
        String filePath = "";
        // /benz
        String projectPath = request.getContextPath();
        if (StringUtils.isBlank(savePath)) {
            // ?D:\apache-tomcat-7.0.47\webapps\benz/userfiles/app/login
            filePath = path + signaturePicAddressPre;
        } else {
            filePath = savePath + projectPath + signaturePicAddressPre;
        }

        Iterator<String> iter = multiRequest.getFileNames();
        while (iter.hasNext()) {
            MultipartFile file = multiRequest.getFile((String) iter.next());
            if (file != null && !file.isEmpty()) {
                String fileName = file.getOriginalFilename();
                FileEmaxDataUtils.createDirectory(filePath);
                String fileNamePath = filePath + File.separator + fileName;
                String relativePath = projectPath + signaturePicAddressPre + File.separator + fileName;

                File localFile = new File(fileNamePath);
                file.transferTo(localFile);
                String md5Hash = MD5Utils.getFileMD5String(localFile);
                // ?
                if (fileName.startsWith(TestdrivePubConstant.IDCARD_PREFIX)) {
                    if (!idCarMD5Hash.equals(md5Hash)) {
                        idcardDriveProtocol.append(card);
                        boolean deletFlag = localFile.delete();
                        if (deletFlag) {
                            logger.info("??");
                        }
                    } else {
                        testDriveApplyInfo.setIdentityCardScanningFile(relativePath);
                    }
                }
                // 
                if (fileName.startsWith(TestdrivePubConstant.DRIVE_PREFIX)) {
                    if (!driveMD5Hash.equals(md5Hash)) {
                        idcardDriveProtocol.append(drive);
                        boolean deletFlag = localFile.delete();
                        if (deletFlag) {
                            logger.info("?!");
                        }
                    } else {
                        testDriveApplyInfo.setDriversLicenseScanningFile(relativePath);
                    }
                }
                // ????
                if (fileName.startsWith(TestdrivePubConstant.PROTOCOL_PREFIX)) {
                    if (!protocolMD5Hash.equals(md5Hash)) {
                        idcardDriveProtocol.append(protocol);
                        boolean deletFlag = localFile.delete();
                        if (deletFlag) {
                            logger.info("?????");
                        }
                    } else {
                        testDriveApplyInfo.setNumberSignature(relativePath);
                    }
                }
            }
        }
        // ????1?1?
        String driveStatus = testDriveApplyInfo.getDriveStatus();
        if ((StringUtils.isNotBlank(driveStatus) && (Integer.parseInt(driveStatus) < 1))
                || StringUtils.isBlank(driveStatus)) {
            testDriveApplyInfo.setDriveStatus("1");// ??
        }
        testDriveApplyInfoService.save(testDriveApplyInfo);
    } else {
        jsonMap = this.saveJson(TestdrivePubConstant.SUCCESS_STATE, "??", "");
        return TestdrivePubUtils.loggerJsonMap(jsonMap);
    }

    if (StringUtils.isNotBlank(idcardDriveProtocol)) {
        jsonMap = this.saveJson(TestdrivePubConstant.ERROR_STATE, "", idcardDriveProtocol.toString());
        return TestdrivePubUtils.loggerJsonMap(jsonMap);
    } else {
        jsonMap = this.saveJson(TestdrivePubConstant.SUCCESS_STATE, TestdrivePubConstant.SUCCESS,
                idcardDriveProtocol.toString());
    }
    String appJson = TestdrivePubUtils.loggerJsonMap(jsonMap);

    if (isDebugLogger) {
        logger.debug("??--uploadSignature----end---");
    }
    return appJson;
}

From source file:cn.mk.ndms.modules.lease.web.controller.LeaseController.java

@RequestMapping(value = "upload", method = RequestMethod.POST)
@ResponseBody/*from   w  w  w .  java  2s.c o  m*/
public AjaxBean upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile file = multiRequest.getFile((String) iter.next());
                if (file != null) {
                    String fileName = file.getOriginalFilename();
                    String path1 = Thread.currentThread().getContextClassLoader().getResource("").getPath()
                            + "file" + File.separator;
                    //  ???
                    String path2 = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + fileName;
                    String path = path1 + path2;
                    File localFile = new File(path);
                    file.transferTo(localFile);
                    Lease lease = leaseService.findOne(request.getParameter("id"));
                    lease.setFilePath(path2);
                    leaseService.update(lease);
                }
            }
        }
        return AjaxBean.getInstance("success");
    } catch (Exception ex) {
        return AjaxBean.getInstance("error", ex.getMessage());
    }
}

From source file:com.daoke.mobileserver.user.controller.UserController.java

/**
 * ?//from   w  ww  .  ja va 2 s  .  c om
 *
 * @param appKey
 * @param accountID
 * @param request
 * @return
 */
@RequestMapping("/uploadHeadImage")
public @ResponseBody CommonJsonResult uploadImage(@RequestParam String appKey, @RequestParam String accountID,
        HttpServletRequest request) {
    CommonJsonResult res = new CommonJsonResult();
    String appkey = ConstantsUtil.getAppKey(appKey);
    String secret = ConstantsUtil.getSecret(appKey);
    String headImageUrl = "";

    try {
        //url
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile file = multiRequest.getFile(iter.next());
                String fileResultUrl = customService.saveFile(appkey, secret, file, saveFile);
                CommonJsonResult fileResult = (CommonJsonResult) JsonMapper.fromJson(fileResultUrl,
                        CommonJsonResult.class);
                Map<String, String> param = (Map<String, String>) fileResult.getRESULT();
                headImageUrl = param.get("url");
                break;
            }
        }

        if (headImageUrl != null) {
            if (userGradeService.uploadHeadImage(accountID, headImageUrl) > 0) {
                res.setERRORCODE(ConstantsUtil.ERRORCODE_OK);
                Map<String, String> map = new HashMap<String, String>();
                map.put("headImageUrl", headImageUrl);
                res.setRESULT(map);
            } else {
                res.setERRORCODE(ConstantsUtil.ERRORCODE_SERVICE_ERROR);
                res.setRESULT("?");
            }
        }

    } catch (Exception e1) {
        e1.printStackTrace();
        logger.error("?:" + e1.getMessage());
        res.setERRORCODE(ConstantsUtil.ERRORCODE_SERVICE_ERROR);
        res.setRESULT("?");
    }

    return res;
}