Example usage for org.springframework.web.multipart MultipartFile getOriginalFilename

List of usage examples for org.springframework.web.multipart MultipartFile getOriginalFilename

Introduction

In this page you can find the example usage for org.springframework.web.multipart MultipartFile getOriginalFilename.

Prototype

@Nullable
String getOriginalFilename();

Source Link

Document

Return the original filename in the client's filesystem.

Usage

From source file:egovframework.oe1.cms.arc.web.EgovOe1ScrinController.java

/**
 * ??   ?./*from   w  w w . j  a va 2  s  .  co m*/
 * @param ?  scrinVO, request, model
 * @return forward:/cms/arc/selectScrin.do";
 * @exception Exception
 */
@RequestMapping(value = "/cms/arc/excelScrinRegist.do")
public String insertExcelScrin(@ModelAttribute("scrinVO") EgovOe1ScrinVO scrinVO,
        final HttpServletRequest request, Map commandMap, Model model) throws Exception {

    // Spring Security
    Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
    if (!isAuthenticated) {
        return "/cms/com/EgovLoginUsr"; // ? ??
    }

    // 
    EgovOe1LoginVO user = (EgovOe1LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
    scrinVO.setFrstRegisterId(user.getMberId());

    String sCmd = commandMap.get("cmd") == null ? "" : (String) commandMap.get("cmd");
    if (sCmd.equals("")) {
        return "/cms/arc/EgovExcelScrinRegist";
    }
    final MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
    final Map<String, MultipartFile> files = multiRequest.getFileMap();

    Iterator<Entry<String, MultipartFile>> itr = files.entrySet().iterator();
    MultipartFile file;

    while (itr.hasNext()) {
        Entry<String, MultipartFile> entry = itr.next();

        file = entry.getValue();
        if (!"".equals(file.getOriginalFilename())) {
            // ? ??    .
            egovOe1ScrinService.deleteExcelScrin();

            InputStream is = null;
            try {
                is = file.getInputStream();
                excelService.uploadExcel("egovOe1ScrinDAO.inserExceltScrin", is, 4);
            } catch (Exception e) {
                throw e;
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (Exception e) {
                    // log none
                    log.info(e.getMessage());
                }
            }
        }
    }

    return "forward:/cms/arc/selectScrin.do";
}

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

/**
 * ???????/* w  w  w  .  j  av a  2 s.  co  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:com.portal.controller.AdminController.java

@RequestMapping(value = "/employes/update", method = RequestMethod.POST)
public String submitUpdateEmployee(HttpServletRequest request, @RequestParam("id") int id,
        @ModelAttribute("employeedto") EmployeeDTO employeedto,
        @RequestParam(value = "avatarFile", required = false) MultipartFile avatar) throws Exception {

    //        Employee employee=new Employee();
    Employee employee = portalService.getEmployee(id);

    if (!avatar.isEmpty() && avatar.getContentType().equals("image/jpeg")) {
        portalService.saveFile(//from   ww  w  .jav a 2s.c o  m
                request.getServletContext().getRealPath("/template/img/") + "/" + avatar.getOriginalFilename(),
                avatar);
        employee.setAvatar(avatar.getOriginalFilename());
    }

    //        employee.setId(id);
    employee.setName(employeedto.getName());
    employee.setDepartment(portalService.getDepartment(employeedto.getDepartment()));
    employee.setPosition(portalService.getPosition(employeedto.getPosition()));
    employee.setPhone(employeedto.getPhone());
    employee.setEmail(employeedto.getEmail());
    employee.setDescription(employeedto.getDescription());
    portalService.saveEmployee(employee);

    return "redirect:/admin/employes";
}

From source file:org.pdfgal.pdfgalweb.services.impl.WatermarkServiceImpl.java

@Override
public DownloadForm putWatermark(final MultipartFile file, final String text, final CustomColor customColor,
        final Float alpha, final WatermarkPosition watermarkPosition, final String pages,
        final HttpServletResponse response) throws Exception {

    DownloadForm result = new DownloadForm();

    if (!file.isEmpty() && StringUtils.isNotBlank(text) && customColor != null && alpha != null
            && watermarkPosition != null && response != null) {

        final String originalName = file.getOriginalFilename();
        final String inputUri = this.fileUtils.saveFile(file);
        final String outputUri = this.fileUtils.getAutogeneratedName(originalName);

        // File is watermarked
        try {// ww  w  .  ja  va 2s.  c  o  m
            final List<Integer> pagesList = this.getPages(pages);
            this.pdfGal.putWatermark(inputUri, outputUri, text, customColor.getColor(), alpha,
                    watermarkPosition, pagesList);
        } catch (COSVisitorException | IOException | IllegalArgumentException e) {
            // Temporal files are deleted from system
            this.fileUtils.delete(inputUri);
            this.fileUtils.delete(outputUri);
            throw e;
        }

        // Temporal files are deleted from system
        this.fileUtils.delete(inputUri);

        result = new DownloadForm(outputUri, originalName);
    }

    return result;
}

From source file:com.osc.edu.chapter4.customers.CustomersController.java

@RequestMapping("/updateCustomers")
public String updateCustomers(@RequestParam(value = "imgFile", required = false) MultipartFile imgFile,
        @ModelAttribute @Valid CustomersDto customers, BindingResult results, SessionStatus status,
        HttpSession session) {/* w ww .  java  2s  .  c  om*/

    if (results.hasErrors()) {
        logger.debug("results : [{}]", results);
        return "customers/form";
    }

    try {
        if (imgFile != null && !imgFile.getOriginalFilename().equals("")) {
            String fileName = imgFile.getOriginalFilename();
            String destDir = session.getServletContext().getRealPath("/upload");

            File dirPath = new File(destDir);
            if (!dirPath.exists()) {
                boolean created = dirPath.mkdirs();
                if (!created) {
                    throw new Exception("Fail to create a directory for movie image. [" + destDir + "]");
                }
            }

            IOUtils.copy(imgFile.getInputStream(), new FileOutputStream(new File(destDir, fileName)));

            logger.debug("Upload file({}) saved to [{}].", fileName, destDir);
        }
        customersService.updateCustomers(customers);
        status.setComplete();
    } catch (Exception e) {
        logger.debug("Exception has occurred. ", e);
    }

    return "redirect:/customers/getCustomersList.do";
}

From source file:com.osc.edu.chapter4.customers.CustomersController.java

@RequestMapping("/insertCustomers")
public String insertCustomers(@RequestParam(value = "imgFile", required = false) MultipartFile imgFile,
        @ModelAttribute @Valid CustomersDto customers, BindingResult results, SessionStatus status,
        HttpSession session) {/*w ww . j a v a  2  s.  c o m*/

    if (results.hasErrors()) {
        logger.debug("results : [{}]", results);
        return "customers/form";
    }

    try {
        if (imgFile != null && !imgFile.getOriginalFilename().equals("")) {
            String fileName = imgFile.getOriginalFilename();
            String destDir = session.getServletContext().getRealPath("/upload");

            File dirPath = new File(destDir);
            if (!dirPath.exists()) {
                boolean created = dirPath.mkdirs();
                if (!created) {
                    throw new Exception("Fail to create a directory for movie image. [" + destDir + "]");
                }
            }

            IOUtils.copy(imgFile.getInputStream(), new FileOutputStream(new File(destDir, fileName)));

            logger.debug("Upload file({}) saved to [{}].", fileName, destDir);
        }

        customersService.insertCustomers(customers);
        status.setComplete();
    } catch (Exception e) {
        logger.debug("Exception has occurred. ", e);
    }

    return "redirect:/customers/getCustomersList.do";
}

From source file:edu.dfci.cccb.mev.controllers.HeatmapController.java

@RequestMapping(params = "format=tsv", method = POST)
@ResponseBody// w  w w  .  j av a 2  s.  c o m
public String add(@RequestParam("filedata") MultipartFile data) throws InvalidHeatmapFormatException {
    String name = data.getOriginalFilename();
    String id = name;
    if (heatmaps.contains(id))
        for (int count = 1; heatmaps.contains(id = name + "-" + count); count++)
            ;
    put(id, data);
    return id;
}

From source file:com.osc.edu.chapter4.employees.EmployeesController.java

@RequestMapping("/insertEmployees")
public String insertEmployees(@RequestParam(value = "imgFile", required = false) MultipartFile imgFile,
        @ModelAttribute @Valid EmployeesDto employees, BindingResult results, SessionStatus status,
        HttpSession session) {//from w  ww . j a v a 2s  .com

    if (results.hasErrors()) {
        logger.debug("results : [{}]", results);
        return "employees/form";
    }

    try {
        if (imgFile != null && !imgFile.getOriginalFilename().equals("")) {
            String fileName = imgFile.getOriginalFilename();
            String destDir = session.getServletContext().getRealPath("/upload");

            File dirPath = new File(destDir);
            if (!dirPath.exists()) {
                boolean created = dirPath.mkdirs();
                if (!created) {
                    throw new Exception("Fail to create a directory for movie image. [" + destDir + "]");
                }
            }

            IOUtils.copy(imgFile.getInputStream(), new FileOutputStream(new File(destDir, fileName)));

            logger.debug("Upload file({}) saved to [{}].", fileName, destDir);
        }

        employeesService.insertEmployees(employees);
        status.setComplete();
    } catch (Exception e) {
        logger.debug("Exception has occurred. ", e);
    }

    return "redirect:/employees/getEmployeesList.do";
}

From source file:com.osc.edu.chapter4.employees.EmployeesController.java

@RequestMapping("/updateEmployees")
public String updateEmployees(@RequestParam(value = "imgFile", required = false) MultipartFile imgFile,
        @ModelAttribute @Valid EmployeesDto employees, BindingResult results, SessionStatus status,
        HttpSession session) {//from   w ww. j  av a  2  s. com

    if (results.hasErrors()) {
        logger.debug("results : [{}]", results);
        return "employees/form";
    }

    try {
        if (imgFile != null && !imgFile.getOriginalFilename().equals("")) {
            String fileName = imgFile.getOriginalFilename();
            String destDir = session.getServletContext().getRealPath("/upload");

            File dirPath = new File(destDir);
            if (!dirPath.exists()) {
                boolean created = dirPath.mkdirs();
                if (!created) {
                    throw new Exception("Fail to create a directory for movie image. [" + destDir + "]");
                }
            }

            IOUtils.copy(imgFile.getInputStream(), new FileOutputStream(new File(destDir, fileName)));

            logger.debug("Upload file({}) saved to [{}].", fileName, destDir);
        }

        employeesService.updateEmployees(employees);
        status.setComplete();
    } catch (Exception e) {
        logger.debug("Exception has occurred. ", e);
    }

    return "redirect:/employees/getEmployeesList.do";
}

From source file:gateway.controller.util.GatewayUtil.java

/**
 * Handles the uploaded file from the data/file endpoint. This will push the file to S3, and then modify the content
 * of the job to reference the new S3 location of the file.
 * /*from w w  w .  j  a v a 2  s.c om*/
 * @param jobId
 *            The Id of the Job, used for generating a unique S3 bucket file name.
 * @param job
 *            The ingest job, containing the DataResource metadata
 * @param file
 *            The file to be uploaded
 * @return The modified job, with the location of the S3 file added to the metadata
 */
public IngestJob pushS3File(String jobId, IngestJob job, MultipartFile file)
        throws AmazonServiceException, AmazonClientException, IOException {
    // The content length must be specified.
    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentLength(file.getSize());
    // Send the file to S3. The key corresponds with the S3 file name.
    String fileKey = String.format("%s-%s", jobId, file.getOriginalFilename());
    s3Client.putObject(AMAZONS3_BUCKET_NAME, fileKey, file.getInputStream(), metadata);
    // Note the S3 file path in the Ingest Job.
    // Attach the file to the FileLocation object
    FileLocation fileLocation = new S3FileStore(AMAZONS3_BUCKET_NAME, fileKey, file.getSize(), AMAZONS3_DOMAIN);
    ((FileRepresentation) job.getData().getDataType()).setLocation(fileLocation);
    logger.log(String.format("S3 File for Job %s Persisted to %s:%s", jobId, AMAZONS3_BUCKET_NAME, fileKey),
            PiazzaLogger.INFO);
    return job;
}