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

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

Introduction

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

Prototype

boolean isEmpty();

Source Link

Document

Return whether the uploaded file is empty, that is, either no file has been chosen in the multipart form or the chosen file has no content.

Usage

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

@Override
public String savePayvoucher(HttpServletRequest request, String user_id, int main_id,
        JpaAttachment.Type file_type, String description) throws BusinessException {
    String result = "";
    try {//  w ww . j  a va  2s .c  om
        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", "");
            log.info("path=", path);
            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.payvoucher.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);
                            result = p.getRight();
                        } else {
                            Attachment t = new Attachment();
                            if (StringUtils.isNotBlank(description)) {
                                t.setDescription(description);
                            }
                            t.setMainId(main_id);
                            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);
                            result = p.getRight();
                        }
                    }
                }
            }
        }

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

From source file:ru.org.linux.topic.AddTopicController.java

private String processUploadImage(HttpServletRequest request) throws IOException, ScriptErrorException {
    if (request instanceof MultipartHttpServletRequest) {
        MultipartFile multipartFile = ((MultipartRequest) request).getFile("image");
        if (multipartFile != null && !multipartFile.isEmpty()) {
            File uploadedFile = File.createTempFile("preview", "",
                    new File(configuration.getPathPrefix() + "/linux-storage/tmp/"));
            String image = uploadedFile.getPath();
            if ((uploadedFile.canWrite() || uploadedFile.createNewFile())) {
                try {
                    logger.debug("Transfering upload to: " + image);
                    multipartFile.transferTo(uploadedFile);
                    return image;
                } catch (Exception e) {
                    throw new ScriptErrorException("Failed to write uploaded file", e);
                }/*  ww  w . j  ava  2 s  .com*/
            } else {
                logger.info("Bad target file name: " + image);
            }
        }
    }

    return null;
}

From source file:miage.ecom.web.admin.controller.ProductImage.java

@RequestMapping(value = "/product/{id}/image", method = RequestMethod.POST)
public ResponseEntity<String> create(@PathVariable("id") int productId,
        @RequestParam("image") MultipartFile image) {

    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.set("Content-type", "text/html");

    String success = null;/*from  w  w w  . j  av a2 s. c o m*/
    String msg = null;
    String imageUrl = "";

    Product product = productFacade.find(productId);

    if (product == null) {
        success = "false";
        msg = "Ce produit n'existe pas / plus";
    }

    if (image.isEmpty()) {
        success = "false";
        msg = "Impossible de sauvegarder l'image";
    }

    if (!image.getContentType().contains("image")) {
        success = "false";
        msg = "Format de fichier non valide";
    }

    if (success == null) {
        try {
            URL thumbUrl = imageManager.uploadThumb(image.getInputStream(), 200);

            if (thumbUrl != null) {

                imageUrl = thumbUrl.toString();
                product.setImage(imageUrl);

                productFacade.edit(product);

                success = "true";

            } else {
                success = "false";
                msg = "Impossible de gnrer l'image";
            }
        } catch (Exception ex) {
            success = "false";
            msg = "Impossible de gnrer l'image : " + ex.getMessage();
        }
    }

    return new ResponseEntity<String>(
            "{success:" + success + ",msg:\"" + msg + "\",image:\"" + imageUrl + "\"}", responseHeaders,
            HttpStatus.OK);
}

From source file:org.openbaton.marketplace.api.RestVNFPackage.java

private VNFPackageMetadata onboard(MultipartFile vnfPackage) throws

IOException, VimException, NotFoundException, SQLException, PluginException, ImageRepositoryNotEnabled,
        NoSuchAlgorithmException, ArchiveException, SDKException, NumberOfImageExceededException,
        AlreadyExistingException, PackageIntegrityException, FailedToUploadException {

    log.debug("onboard....");
    if (!vnfPackage.isEmpty()) {
        byte[] bytes = vnfPackage.getBytes();
        String fileName = vnfPackage.getOriginalFilename();

        VNFPackageMetadata vnfPackageMetadata = vnfPackageManagement.add(fileName, bytes, false);
        return vnfPackageMetadata;
    } else {/*from   w ww .ja  va 2s .c o  m*/
        throw new IOException("File is an empty file!");
    }
}

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 {//w  w  w . ja  va  2  s  . com
        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: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 {/*from www  . ja  v a 2s.c o m*/
        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:org.shareok.data.webserv.RestDspaceDataController.java

@RequestMapping(value = "/rest/{repoTypeStr}/{jobType}", method = RequestMethod.POST)
public ModelAndView sshDspaceSaFImporter(HttpServletRequest request, RedirectAttributes redirectAttrs,
        @PathVariable("repoTypeStr") String repoTypeStr,
        @RequestParam(value = "localFile", required = false) MultipartFile file,
        @PathVariable("jobType") String jobType, @ModelAttribute("SpringWeb") DspaceApiJob job) {
    ModelAndView model = new ModelAndView();

    String filePath = "";

    logger.debug("Start to process the DSpace Rest API request...");

    try {/*from   w  w  w . j av a2 s  .c o  m*/
        if (null == file || file.isEmpty()) {
            String localFile = (String) request.getParameter("localFile");
            if (!DocumentProcessorUtil.isEmptyString(localFile)) {
                filePath = localFile;
                String safDir = (String) request.getParameter("localSafDir");
                if (!DocumentProcessorUtil.isEmptyString(safDir)) {
                    filePath = safDir + File.separator + filePath;
                }
                String folder = (String) request.getParameter("localFolder");
                if (!DocumentProcessorUtil.isEmptyString(folder)) {
                    filePath = folder + File.separator + filePath;
                }
                String journalSearch = (String) request.getParameter("journalSearch");
                if (null != journalSearch && journalSearch.equals("1")) {
                    filePath = ShareokdataManager.getDspaceUploadPath() + File.separator + filePath;
                } else {
                    filePath = ShareokdataManager.getOuhistoryUploadPath() + File.separator + filePath;
                }
            } else {
                filePath = (String) request.getParameter("remoteFileUri");
            }
        } else {
            filePath = ServiceUtil.saveUploadedFile(file,
                    ShareokdataManager.getDspaceRestImportPath(jobType + "-" + repoTypeStr));
        }
    } catch (Exception ex) {
        logger.error("Cannot upload the file for DSpace import using REST API.", ex);
        model.addObject("errorMessage", "Cannot get the server list");
        model.setViewName("serverError");
        return model;
    }

    DspaceRepoServer server = (DspaceRepoServer) serverService.findServerById(job.getServerId());
    String userId = String.valueOf(request.getSession().getAttribute("userId"));
    job.setUserId(Long.valueOf(userId));
    job.setCollectionId(server.getPrefix() + "/" + job.getCollectionId());
    job.setRepoType(DataUtil.getRepoTypeIndex(repoTypeStr));
    job.setType(DataUtil.getJobTypeIndex(jobType, repoTypeStr));
    job.setStatus(Arrays.asList(RedisUtil.REDIS_JOB_STATUS).indexOf("created"));
    job.setFilePath(filePath);
    job.setStartTime(new Date());
    job.setEndTime(null);

    try {
        RedisJob returnedJob = taskManager.execute(job);

        if (null == returnedJob) {
            throw new JobProcessingException("Null job object returned after processing!");
        }

        int statusIndex = job.getStatus();
        String isFinished = (statusIndex == 2 || statusIndex == 6) ? "true" : "false";

        RedirectView view = new RedirectView();
        view.setContextRelative(true);
        view.setUrl("/report/job/" + String.valueOf(returnedJob.getJobId()));
        model.setView(view);
        redirectAttrs.addFlashAttribute("host",
                serverService.findServerById(returnedJob.getServerId()).getHost());
        redirectAttrs.addFlashAttribute("collection",
                DspaceDataUtil.DSPACE_REPOSITORY_HANDLER_ID_PREFIX + job.getCollectionId());
        redirectAttrs.addFlashAttribute("isFinished", isFinished);
        redirectAttrs.addFlashAttribute("reportPath", DataHandlersUtil
                .getJobReportFilePath(DataUtil.JOB_TYPES[returnedJob.getType()], returnedJob.getJobId()));
        WebUtil.outputJobInfoToModel(redirectAttrs, returnedJob);
    } catch (Exception ex) {
        logger.error("Cannot process the job of DSpace import using REST API.", ex);
        model.addObject("errorMessage", "Cannot process the job of DSpace import using REST API.");
        model.setViewName("serverError");
    }
    return model;
}

From source file:ru.codemine.ccms.router.TaskRouter.java

@Secured("ROLE_USER")
@RequestMapping(value = "/tasks/addfile", method = RequestMethod.POST)
public String addFileToTask(@RequestParam("file") MultipartFile file, @RequestParam("id") Integer id) {
    Task task = taskService.getById(id);
    Employee employee = employeeService.getCurrentUser();

    if (file.isEmpty())
        return "redirect:/tasks/taskinfo?id=" + task.getId();

    if (employee.equals(task.getCreator()) || task.getPerformers().contains(employee)) {
        String filename = settingsService.getStorageTasksPath() + UUID.randomUUID().toString();
        String viewname = file.getOriginalFilename();
        File targetFile = new File(filename);

        DataFile targetDataFile = new DataFile(employee);
        targetDataFile.setFilename(filename);
        targetDataFile.setViewName(viewname);
        targetDataFile.setSize(file.getSize());
        targetDataFile.setTypeByExtension();

        try {//from  ww  w .  j  av  a 2  s  . c o  m
            file.transferTo(targetFile);
        } catch (IOException | IllegalStateException ex) {
            log.error("    " + viewname + ", : "
                    + ex.getLocalizedMessage());
            return "redirect:/tasks/taskinfo?id=" + task.getId();
        }

        dataFileService.create(targetDataFile);
        task.getFiles().add(targetDataFile);
        taskService.update(task);
    }

    return "redirect:/tasks/taskinfo?id=" + task.getId();
}

From source file:csns.web.controller.FileManagerController.java

@RequestMapping("/file/upload")
public String upload(@RequestParam(required = false) Long parentId,
        @RequestParam("file") MultipartFile uploadedFile, ModelMap models) {
    File parent = null;/*from ww  w. j a v  a  2s  .  c  o m*/
    String redirectUrl = "redirect:/file/";
    if (parentId != null) {
        parent = fileDao.getFile(parentId);
        redirectUrl += "view?id=" + parentId;
    }

    if (!uploadedFile.isEmpty()) {
        User user = SecurityUtils.getUser();
        long diskQuota = user.getDiskQuota() * 1024L * 1024L;
        long diskUsage = fileDao.getDiskUsage(user);
        if (diskUsage + uploadedFile.getSize() > diskQuota) {
            models.put("message", "error.file.quota.exceeded");
            return "error";
        }

        File file = new File();
        file.setName(uploadedFile.getOriginalFilename());
        file.setType(uploadedFile.getContentType());
        file.setSize(uploadedFile.getSize());
        file.setOwner(user);
        file.setRegular(true);
        if (parent != null) {
            file.setParent(parent);
            file.setPublic(parent.isPublic());
        }
        file = fileDao.saveFile(file);

        fileIO.save(file, uploadedFile);
    }

    return redirectUrl;
}