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:me.doshou.admin.maintain.editor.web.controller.OnlineEditorController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody// ww w.  j  ava2  s. c  o m
public AjaxUploadResponse upload(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("parentPath") String parentPath, @RequestParam("conflict") String conflict,
        @RequestParam(value = "files[]", required = false) MultipartFile[] files)
        throws UnsupportedEncodingException {

    String rootPath = sc.getRealPath(ROOT_DIR);
    parentPath = URLDecoder.decode(parentPath, Constants.ENCODING);
    File parent = new File(rootPath + File.separator + parentPath);

    //The file upload plugin makes use of an Iframe Transport module for browsers like Microsoft Internet Explorer and Opera, which do not yet support XMLHTTPRequest file uploads.
    response.setContentType("text/plain");

    AjaxUploadResponse ajaxUploadResponse = new AjaxUploadResponse();

    if (ArrayUtils.isEmpty(files)) {
        return ajaxUploadResponse;
    }

    for (MultipartFile file : files) {
        String filename = file.getOriginalFilename();
        long size = file.getSize();
        try {
            File current = new File(parent, filename);
            if (current.exists() && "ignore".equals(conflict)) {
                ajaxUploadResponse.add(filename, size, MessageUtils.message("upload.conflict.error"));
                continue;
            }
            String url = FileUploadUtils.upload(request, parentPath, file, ALLOWED_EXTENSION, MAX_SIZE, false);
            String deleteURL = viewName("/delete") + "?paths=" + URLEncoder.encode(url, Constants.ENCODING);

            ajaxUploadResponse.add(filename, size, url, deleteURL);

            continue;
        } catch (IOException e) {
            LogUtils.logError("file upload error", e);
            ajaxUploadResponse.add(filename, size, MessageUtils.message("upload.server.error"));
            continue;
        } catch (InvalidExtensionException e) {
            ajaxUploadResponse.add(filename, size, MessageUtils.message("upload.not.allow.extension"));
            continue;
        } catch (FileUploadBase.FileSizeLimitExceededException e) {
            ajaxUploadResponse.add(filename, size, MessageUtils.message("upload.exceed.maxSize"));
            continue;
        } catch (FileNameLengthLimitExceededException e) {
            ajaxUploadResponse.add(filename, size, MessageUtils.message("upload.filename.exceed.length"));
            continue;
        }
    }
    return ajaxUploadResponse;
}

From source file:com.pantuo.service.impl.AttachmentServiceImpl.java

public void saveAttachment(HttpServletRequest request, String user_id, int main_id,
        JpaAttachment.Type file_type, String description) throws BusinessException {

    try {//from   w  ww .  ja v a 2  s  .  c o  m
        CustomMultipartResolver multipartResolver = new CustomMultipartResolver(
                request.getSession().getServletContext());
        log.info("userid:{},main_id:{},file_type:{}", user_id, main_id, file_type);
        if (multipartResolver.isMultipart(request)) {
            String path = request.getSession().getServletContext()
                    .getRealPath(com.pantuo.util.Constants.FILE_UPLOAD_DIR).replaceAll("WEB-INF", "");
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile file = multiRequest.getFile(iter.next());
                if (file != null && !file.isEmpty()) {
                    String oriFileName = file.getOriginalFilename();
                    String fn = file.getName();
                    if (StringUtils.isNoneBlank(oriFileName)) {

                        String storeName = GlobalMethods
                                .md5Encrypted((System.currentTimeMillis() + oriFileName).getBytes());
                        Pair<String, String> p = FileHelper.getUploadFileName(path,
                                storeName += FileHelper.getFileExtension(oriFileName, true));
                        File localFile = new File(p.getLeft());
                        file.transferTo(localFile);
                        AttachmentExample example = new AttachmentExample();
                        AttachmentExample.Criteria criteria = example.createCriteria();
                        criteria.andMainIdEqualTo(main_id);
                        criteria.andUserIdEqualTo(user_id);
                        criteria.andTypeEqualTo(JpaAttachment.Type.user_qualifi.ordinal());
                        List<Attachment> attachments = attachmentMapper.selectByExample(example);
                        if (attachments.size() > 0) {
                            Attachment t = attachments.get(0);
                            t.setUpdated(new Date());
                            t.setName(oriFileName);
                            t.setUrl(p.getRight());
                            attachmentMapper.updateByPrimaryKey(t);

                        } else {
                            Attachment t = new Attachment();
                            if (StringUtils.isNotBlank(description)) {
                                t.setDescription(description);
                            }
                            t.setMainId(main_id);
                            if (StringUtils.equals(fn, "licensefile")) {
                                t.setType(JpaAttachment.Type.license.ordinal());
                            } else if (fn.indexOf("qua") != -1) {
                                t.setType(JpaAttachment.Type.u_fj.ordinal());
                            } else if (StringUtils.equals(fn, "taxfile")) {
                                t.setType(JpaAttachment.Type.tax.ordinal());
                            } else if (StringUtils.equals(fn, "taxpayerfile")) {
                                t.setType(JpaAttachment.Type.taxpayer.ordinal());
                            } else if (StringUtils.equals(fn, "user_license")) {
                                t.setType(JpaAttachment.Type.user_license.ordinal());
                            } else if (StringUtils.equals(fn, "user_code")) {
                                t.setType(JpaAttachment.Type.user_code.ordinal());
                            } else if (StringUtils.equals(fn, "user_tax")) {
                                t.setType(JpaAttachment.Type.user_tax.ordinal());
                            } else {
                                t.setType(file_type.ordinal());
                            }
                            t.setCreated(new Date());
                            t.setUpdated(t.getCreated());
                            t.setName(oriFileName);
                            t.setUrl(p.getRight());
                            t.setUserId(user_id);
                            attachmentMapper.insert(t);
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        log.error("saveAttachment", e);
        throw new BusinessException("saveAttachment-error", e);
    }

}

From source file:cn.org.once.cstack.service.impl.ApplicationServiceImpl.java

@Override
@Transactional// w w w  . jav  a2  s .  co  m
public Application deploy(MultipartFile file, Application application) throws ServiceException, CheckException {
    try {
        // get app with all its components
        String filename = file.getOriginalFilename();
        String containerId = application.getServer().getContainerID();
        String tempDirectory = dockerService.getEnv(containerId, "CU_TMP");
        fileService.sendFileToContainer(containerId, tempDirectory, file, null, null);
        String contextPath = NamingUtils.getContext.apply(filename);
        @SuppressWarnings("serial")
        Map<String, String> kvStore = new HashMap<String, String>() {
            {
                put("CU_USER", application.getUser().getLogin());
                put("CU_PASSWORD", application.getUser().getPassword());
                put("CU_FILE", filename);
                put("CU_CONTEXT_PATH", contextPath);
            }
        };
        String result = dockerService.execCommand(containerId, RemoteExecAction.DEPLOY.getCommand(kvStore));
        logger.info("Deploy command {}", result);
        Deployment deployment = deploymentService.create(application, DeploymentType.from(filename),
                contextPath);
        application.addDeployment(deployment);
        application.setDeploymentStatus(Application.ALREADY_DEPLOYED);

        // If application is anything else than .jar or ROOT.war
        // we need to clean for the next deployment.
        if (!"/".equalsIgnoreCase(contextPath)) {
            @SuppressWarnings("serial")
            HashMap<String, String> kvStore2 = new HashMap<String, String>() {
                {
                    put("CU_TARGET", Paths.get(tempDirectory, filename).toString());
                }
            };
            dockerService.execCommand(containerId, RemoteExecAction.CLEAN_DEPLOY.getCommand(kvStore2));
        }
    } catch (Exception e) {
        throw new ServiceException(e.getLocalizedMessage(), e);
    }

    return application;
}

From source file:com.luna.maintain.editor.web.controller.OnlineEditorController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody//  w w w  .  j a va  2 s  . c om
public AjaxUploadResponse upload(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("parentPath") String parentPath, @RequestParam("conflict") String conflict,
        @RequestParam(value = "files[]", required = false) MultipartFile[] files)
        throws UnsupportedEncodingException {

    String rootPath = sc.getRealPath(ROOT_DIR);
    parentPath = URLDecoder.decode(parentPath, Constants.ENCODING);
    File parent = new File(rootPath + File.separator + parentPath);

    //The file upload plugin makes use of an Iframe Transport module for browsers like Microsoft Internet Explorer and Opera, which do not yet support XMLHTTPRequest file uploads.
    response.setContentType("text/plain");

    AjaxUploadResponse ajaxUploadResponse = new AjaxUploadResponse();

    if (ArrayUtils.isEmpty(files)) {
        return ajaxUploadResponse;
    }

    for (MultipartFile file : files) {
        String filename = file.getOriginalFilename();
        long size = file.getSize();
        try {
            File current = new File(parent, filename);
            if (current.exists() && "ignore".equals(conflict)) {
                ajaxUploadResponse.add(filename, size, MessageUtils.message("upload.conflict.error"));
                continue;
            }
            String url = FileUploadUtils.upload(request, parentPath, file, ALLOWED_EXTENSION, MAX_SIZE, false);
            String deleteURL = viewName("/delete") + "?paths=" + URLEncoder.encode(url, Constants.ENCODING);

            ajaxUploadResponse.add(filename, size, url, deleteURL);

            continue;
        } catch (IOException e) {
            log.error("file upload error", e);
            ajaxUploadResponse.add(filename, size, MessageUtils.message("upload.server.error"));
            continue;
        } catch (InvalidExtensionException e) {
            ajaxUploadResponse.add(filename, size, MessageUtils.message("upload.not.allow.extension"));
            continue;
        } catch (FileUploadBase.FileSizeLimitExceededException e) {
            ajaxUploadResponse.add(filename, size, MessageUtils.message("upload.exceed.maxSize"));
            continue;
        } catch (FileNameLengthLimitExceededException e) {
            ajaxUploadResponse.add(filename, size, MessageUtils.message("upload.filename.exceed.length"));
            continue;
        }
    }
    return ajaxUploadResponse;
}

From source file:com.pantuo.service.impl.AttachmentServiceImpl.java

public void updateAttachments(HttpServletRequest request, String user_id, int main_id,
        JpaAttachment.Type file_type, String description) throws BusinessException {

    try {/*w ww.j a  v  a 2 s  .c om*/
        CustomMultipartResolver multipartResolver = new CustomMultipartResolver(
                request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            String path = request.getSession().getServletContext()
                    .getRealPath(com.pantuo.util.Constants.FILE_UPLOAD_DIR).replaceAll("WEB-INF", "");
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile file = multiRequest.getFile(iter.next());
                if (file != null && !file.isEmpty()) {
                    String oriFileName = file.getOriginalFilename();
                    String fn = file.getName();
                    if (StringUtils.isNoneBlank(oriFileName)) {

                        String storeName = GlobalMethods
                                .md5Encrypted((System.currentTimeMillis() + oriFileName).getBytes());
                        Pair<String, String> p = FileHelper.getUploadFileName(path,
                                storeName += FileHelper.getFileExtension(oriFileName, true));
                        File localFile = new File(p.getLeft());
                        file.transferTo(localFile);
                        AttachmentExample example = new AttachmentExample();
                        AttachmentExample.Criteria criteria = example.createCriteria();
                        criteria.andMainIdEqualTo(main_id);
                        criteria.andUserIdEqualTo(user_id);
                        List<Attachment> attachments = attachmentMapper.selectByExample(example);
                        for (Attachment t : attachments) {
                            if (StringUtils.equals(fn, "licensefile")
                                    && t.getType() == JpaAttachment.Type.license.ordinal()) {
                                t.setUpdated(new Date());
                                t.setName(oriFileName);
                                t.setUrl(p.getRight());
                                attachmentMapper.updateByPrimaryKey(t);
                            }
                            if (StringUtils.equals(fn, "taxfile")
                                    && t.getType() == JpaAttachment.Type.tax.ordinal()) {
                                t.setUpdated(new Date());
                                t.setName(oriFileName);
                                t.setUrl(p.getRight());
                                attachmentMapper.updateByPrimaryKey(t);
                            }
                            if (StringUtils.equals(fn, "taxpayerfile")
                                    && t.getType() == JpaAttachment.Type.taxpayer.ordinal()) {
                                t.setUpdated(new Date());
                                t.setName(oriFileName);
                                t.setUrl(p.getRight());
                                attachmentMapper.updateByPrimaryKey(t);
                            }
                            if (StringUtils.equals(fn, "user_license")
                                    && t.getType() == JpaAttachment.Type.user_license.ordinal()) {
                                t.setUpdated(new Date());
                                t.setName(oriFileName);
                                t.setUrl(p.getRight());
                                attachmentMapper.updateByPrimaryKey(t);
                            }
                            if (StringUtils.equals(fn, "user_tax")
                                    && t.getType() == JpaAttachment.Type.user_tax.ordinal()) {
                                t.setUpdated(new Date());
                                t.setName(oriFileName);
                                t.setUrl(p.getRight());
                                attachmentMapper.updateByPrimaryKey(t);
                            }
                            if (StringUtils.equals(fn, "user_code")
                                    && t.getType() == JpaAttachment.Type.user_code.ordinal()) {
                                t.setUpdated(new Date());
                                t.setName(oriFileName);
                                t.setUrl(p.getRight());
                                attachmentMapper.updateByPrimaryKey(t);
                            }

                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        log.error("saveAttachment", e);
        throw new BusinessException("saveAttachment-error", e);
    }
}

From source file:cz.zcu.kiv.eegdatabase.logic.controller.experiment.AddDataFileController.java

/**
 * Processing of the valid form// w  ww . ja va 2s.  c  om
 */
@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException bindException) throws Exception {
    log.debug("Processing form data.");
    AddDataFileCommand addDataCommand = (AddDataFileCommand) command;
    MultipartHttpServletRequest mpRequest = (MultipartHttpServletRequest) request;
    // the map containing file names mapped to files
    Map m = mpRequest.getFileMap();
    Set set = m.keySet();
    for (Object key : set) {
        MultipartFile file = (MultipartFile) m.get(key);

        if (file == null) {
            log.error("No file was uploaded!");
        } else {
            log.debug("Creating measuration with ID " + addDataCommand.getMeasurationId());
            Experiment experiment = new Experiment();
            experiment.setExperimentId(addDataCommand.getMeasurationId());
            if (file.getOriginalFilename().endsWith(".zip")) {
                ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(file.getBytes()));
                ZipEntry en = zis.getNextEntry();
                while (en != null) {
                    if (en.isDirectory()) {
                        en = zis.getNextEntry();
                        continue;
                    }
                    DataFile data = new DataFile();
                    data.setExperiment(experiment);
                    String name[] = en.getName().split("/");
                    data.setFilename(name[name.length - 1]);
                    data.setDescription(addDataCommand.getDescription());
                    data.setFileContent(Hibernate.createBlob(zis));
                    String[] partOfName = en.getName().split("[.]");
                    data.setMimetype(partOfName[partOfName.length - 1]);
                    dataFileDao.create(data);
                    en = zis.getNextEntry();
                }
            } else {
                log.debug("Creating new Data object.");
                DataFile data = new DataFile();
                data.setExperiment(experiment);

                log.debug("Original name of uploaded file: " + file.getOriginalFilename());
                String filename = file.getOriginalFilename().replace(" ", "_");
                data.setFilename(filename);

                log.debug("MIME type of the uploaded file: " + file.getContentType());
                if (file.getContentType().length() > MAX_MIMETYPE_LENGTH) {
                    int index = filename.lastIndexOf(".");
                    data.setMimetype(filename.substring(index));
                } else {
                    data.setMimetype(file.getContentType());
                }

                log.debug("Parsing the sapmling rate.");
                data.setDescription(addDataCommand.getDescription());

                log.debug("Setting the binary data to object.");
                data.setFileContent(Hibernate.createBlob(file.getBytes()));

                dataFileDao.create(data);
                log.debug("Data stored into database.");
            }
        }
    }

    log.debug("Returning MAV");
    ModelAndView mav = new ModelAndView(
            "redirect:/experiments/detail.html?experimentId=" + addDataCommand.getMeasurationId());
    return mav;
}

From source file:com.baidu.gcrm.materials.web.MaterialsAction.java

/**
 * //from  ww w.  ja  v  a  2 s  .co m
 * 
 * @return
 */
@RequestMapping("/doUploadFile")
@ResponseBody
public Object doUploadFile(MultipartHttpServletRequest multipartRequest, HttpServletResponse response) {
    Iterator<String> it = multipartRequest.getFileNames();
    MultipartFile mpf = null;
    while (it.hasNext()) {
        String fileName = it.next();
        mpf = multipartRequest.getFile(fileName);
        log.debug("===" + fileName + "upload to local sever");
    }

    //
    Attachment attachment = new Attachment();
    attachment.setFieldName(mpf.getName());
    attachment.setName(mpf.getOriginalFilename());
    attachment.setCustomerNumber(-1L);
    attachment.setId(-1L);
    attachment.setTempUrl("");
    //attachment.setType(-1);
    attachment.setUrl("");
    //   attachment.setExit(false);
    try {
        attachment.setBytes(mpf.getBytes());
    } catch (IOException e) {
        log.error("=====" + e.getMessage());
        attachment.setMessage("failed");
        return attachment;
    }

    if (!StringUtils.isEmpty(mpf.getOriginalFilename())) {
        if (mpf.getOriginalFilename().endsWith(".exe")) {
            attachment.setMessage("materials.extension.error");//I18N?code
        } else {
            if (matericalsService.uploadFile(attachment)) {
                attachment.setMessage("success");
            } else {
                attachment.setMessage("failed");
            }
        }
    }

    //?
    String userAgent = multipartRequest.getHeader("user-agent").toLowerCase();
    if (userAgent.indexOf("msie 6") != -1 || userAgent.indexOf("msie 7") != -1
            || userAgent.indexOf("msie 8") != -1 || userAgent.indexOf("msie 9") != -1) {
        return JSONObject.toJSONString(attachment);

    }
    return attachment;
}

From source file:de.iteratec.iteraplan.presentation.dialog.Templates.TemplatesController.java

private MultipartFile uploadTemplate(TemplatesDialogMemory dialogMem, MultipartHttpServletRequest req) {
    TemplateType uploadedType = TemplateType.getTypeFromKey(dialogMem.getTargetTemplateType());
    MultipartFile file = req.getFile(uploadedType.getNameKey() + "_file");

    if (file == null || file.getSize() == 0) {
        dialogMem.setTemplateFileNull(true);
        dialogMem.setWrongFileType(false);
        return null;
    } else {/*from w ww. j a  v a2 s.com*/
        dialogMem.setTemplateFileNull(false);
    }

    String originalFilename = file.getOriginalFilename();
    String extension = originalFilename.contains(".")
            ? originalFilename.substring(originalFilename.lastIndexOf('.'))
            : null;
    if (extension == null || !uploadedType.getExtensions().contains(extension)) {
        dialogMem.setWrongFileType(true);
        dialogMem.setTemplateFileNull(false);
        return null;
    } else {
        dialogMem.setWrongFileType(false);
    }
    return file;
}

From source file:org.openmrs.module.radiology.web.controller.RadiologyObsFormController.java

/**
 * Populate complex obs with complex data
 * //from   w  ww .  ja  v a  2  s .  c  o  m
 * @param complexDataFile the obs should be populated with
 * @param obs to be populated
 * @param InputStream of the file
 * @return saved complex obs with complex data
 * @throws IOException
 * @should populate new obs with new complex data
 * @should populate obs with new complex data
 * @should throw exception for new obs with empty file
 */
private Obs populateObsWithComplexData(MultipartFile complexDataFile, Obs obs,
        InputStream complexDataInputStream) throws IOException {

    boolean isComplexDataFileNotNullAndNotEmpty = complexDataFile != null && !complexDataFile.isEmpty();
    if (isComplexDataFileNotNullAndNotEmpty) {
        obs.setComplexData(new ComplexData(complexDataFile.getOriginalFilename(), complexDataInputStream));
        return obs;
    } else if (obs.getId() != null) {
        obs.setComplexData(obsService.getComplexObs(obs.getId(), null).getComplexData());
        return obs;
    } else {
        throw new IOException("Obs.invalidImage");
    }
}

From source file:edu.wisc.doit.tcrypt.controller.EncryptController.java

@RequestMapping(value = "/encryptFile", method = RequestMethod.POST)
public ModelAndView encryptFile(@RequestParam("fileToEncrypt") MultipartFile file,
        @RequestParam("selectedServiceName") String serviceName, HttpServletResponse response)
        throws Exception {
    if (file.isEmpty()) {
        ModelAndView modelAndView = encryptTextInit();
        modelAndView.addObject("selectedServiceName", serviceName);
        return modelAndView;
    }/*w w  w  .  j  av a2  s .com*/

    final FileEncrypter fileEncrypter = this.getFileEncrypter(serviceName);
    final String filename = FilenameUtils.getName(file.getOriginalFilename());

    response.setHeader("Content-Type", "application/x-tar");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + ".tar" + "\"");

    final long size = file.getSize();
    try (final InputStream inputStream = file.getInputStream();
            final ServletOutputStream outputStream = response.getOutputStream()) {

        fileEncrypter.encrypt(filename, (int) size, inputStream, outputStream);
    }

    return null;
}