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.zte.gu.webtools.web.ddm.DdmController.java

@RequestMapping(method = RequestMethod.POST)
public ModelAndView scan(@RequestParam(required = true) MultipartFile boardFile,
        @RequestParam(required = true) MultipartFile ruFile, @RequestParam(required = true) String sdrVer,
        HttpSession session) {/*from   ww  w  .jav  a2  s  . c om*/
    List<DdmVersion> versions = ddmService.getAllVersion();
    ModelAndView modelAndView = new ModelAndView("ddm/ddmScan");
    modelAndView.getModelMap().addAttribute("versions", versions);
    if (boardFile.isEmpty()) {
        modelAndView.getModelMap().addAttribute("error", "?");
    }
    if (!ACCEPT_TYPES.contains(boardFile.getContentType())) {
        modelAndView.getModelMap().addAttribute("error", "???");
    }
    if (ruFile.isEmpty()) {
        modelAndView.getModelMap().addAttribute("error", "RU?");
    }
    if (!ACCEPT_TYPES.contains(ruFile.getContentType())) {
        modelAndView.getModelMap().addAttribute("error", "RU???");
    }

    InputStream boardInput = null;
    InputStream ruInput = null;
    try {
        boardInput = boardFile.getInputStream();
        ruInput = ruFile.getInputStream();
        File tempZipFile = ddmService.exportXml(boardInput, ruInput, sdrVer); //?
        if (tempZipFile != null) {
            session.setAttribute("filePath", tempZipFile.getPath());
            session.setAttribute("fileName", "ddm.zip");
            modelAndView.setViewName("redirect:/download");
        }
    } catch (Exception e) {
        LoggerFactory.getLogger(DdmController.class).warn("download error,", e);
        modelAndView.getModelMap().addAttribute("error", "?" + e.getMessage());
    } finally {
        IOUtils.closeQuietly(boardInput);
        IOUtils.closeQuietly(ruInput);
    }
    return modelAndView;
}

From source file:cs425.yogastudio.controller.SignupController.java

@RequestMapping(value = "/addCustomer", method = RequestMethod.POST)
public String addCustomer(String firstname, String lastname, String email, String username, String password,
        String state, String zip, String street, String city, Model model, HttpSession session,
        @RequestParam("file") MultipartFile file) {

    if (checkUsername(username)) {
        session.setAttribute("nonUniqueMessage", null);

        Customer newCustomer = new Customer(firstname, lastname, email, username, password);
        Address newAddress = new Address(state, zip, street, city);
        //         ShoppingCart shoppingCart = new ShoppingCart(newCustomer);

        if (!file.isEmpty()) {
            try {
                newCustomer.setProductImage(file.getBytes());
            } catch (IOException e) {
                e.printStackTrace();/*from   ww  w  . j  a va 2 s .  c om*/
            }
        }

        newCustomer.addAddress(newAddress);
        customerService.addCustomer(newCustomer);
        //model.addAttribute("newcustomer", newCustomer);
        session.setAttribute("added", newCustomer.getFirstName());
        return "redirect:/signUpSuccess";
    } else {
        session.setAttribute("nonUniqueMessage", "username already exists, try another one");
        return "redirect:/customerSignup";
    }

}

From source file:controllers.admin.PostController.java

@PostMapping("/save")
public String processPost(@RequestPart("postImage") MultipartFile postImage,
        @ModelAttribute(ATTRIBUTE_NAME) @Valid Post post, BindingResult bindingResult,
        @CurrentUserAttached User activeUser, RedirectAttributes model) throws IOException, SQLException {

    String url = "redirect:/admin/posts/all";

    if (post.getImage() == null && postImage != null && postImage.isEmpty()) {
        bindingResult.rejectValue("image", "post.image.notnull");
    }/*from  ww w.j ava  2 s  .c om*/

    if (bindingResult.hasErrors()) {
        model.addFlashAttribute(BINDING_RESULT_NAME, bindingResult);
        return url;
    }

    if (postImage != null && !postImage.isEmpty()) {
        logger.info("Aadiendo informacin de la imagen");
        FileImage image = new FileImage();
        image.setName(postImage.getName());
        image.setContentType(postImage.getContentType());
        image.setSize(postImage.getSize());
        image.setContent(postImage.getBytes());
        post.setImage(image);
    }

    post.setAuthor(activeUser);
    if (post.getId() == null) {
        postService.create(post);
    } else {
        postService.edit(post);
    }

    List<String> successMessages = new ArrayList();
    successMessages.add(messageSource.getMessage("message.post.save.success", new Object[] { post.getId() },
            Locale.getDefault()));
    model.addFlashAttribute("successFlashMessages", successMessages);
    return url;
}

From source file:service.AuthorService.java

public ServiceResult registration(Author author, String password, String password2, MultipartFile file)
        throws IOException {
    if (author != null) {
        author.setActiveInt(1);/* www . java  2  s. c o m*/
    }
    ServiceResult result = userService.registration(author, password, password2);
    if (!result.hasErrors() && file != null && !file.isEmpty()) {
        AuthorFile fileEnt = new AuthorFile();
        fileEnt.setAuthor(author);
        saveFile(fileEnt, file);
    }
    return result;
}

From source file:org.iti.agrimarket.view.FileUploadController.java

public String handleFileUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file,
        RedirectAttributes redirectAttributes) {
    if (name.contains("/")) {
        redirectAttributes.addFlashAttribute("message", "Folder separators not allowed");
        return "redirect:/";
    }/*from  www .j a  v a 2s  . c o  m*/
    if (name.contains("/")) {
        redirectAttributes.addFlashAttribute("message", "Relative pathnames not allowed");
        return "redirect:/";
    }

    if (!file.isEmpty()) {
        try {
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(name)));
            FileCopyUtils.copy(file.getInputStream(), stream);
            stream.close();
            redirectAttributes.addFlashAttribute("message", "You successfully uploaded " + name + "!");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("message",
                    "You failed to upload " + name + " => " + e.getMessage());
        }
    } else {
        redirectAttributes.addFlashAttribute("message",
                "You failed to upload " + name + " because the file was empty");
    }

    return "redirect:/index";
}

From source file:com.zb.app.biz.service.impl.FileServiceImpl.java

public Result createFilePath(MultipartFile file, Long... id) {
    // ?/*from   ww  w . ja v  a  2  s.c o m*/
    if (file == null) {
        return Result.failed();
    }
    if (!file.isEmpty()) {
        if (StringUtils.isEmpty(file.getOriginalFilename())) {
            return Result.failed();
        }
        // int lastIndex = StringUtils.lastIndexOf(file.getOriginalFilename(), ".");
        // String suffix = StringUtils.substring(file.getOriginalFilename(), lastIndex);
        String[] suffixArray = StringUtils.split(file.getOriginalFilename(), ".");
        if (Argument.isEmptyArray(suffixArray)) {
            return Result.failed();
        }
        String prefix = null;
        if (Argument.isEmptyArray(id)) {
            prefix = SerialNumGenerator.createSerNo(null, SerialNumGenerator.p_prefix);
        } else {
            prefix = SerialNumGenerator.createSerNo(id[0], SerialNumGenerator.p_prefix);
        }
        String suffix = null;
        if (suffixArray.length == 1) {
            suffix = "jpg";
        } else {
            suffix = suffixArray[suffixArray.length - 1];
        }
        String filePath = prefix + DELIMITER + suffix;
        try {
            // 
            file.transferTo(new File(UPLOAD_TMP_PATH + filePath));
            return Result.success(null, STATIC_TMP_IMG + filePath);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return Result.failed();
        }
    }
    return Result.failed();
}

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

/**
 * Populate complex obs with complex data
 * /*from  w  w  w.  ja v  a2s .  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:org.jasig.portlet.cms.controller.EditPostController.java

private void processPostAttachments(final ActionRequest request, final Post post) throws Exception {
    if (FileUploadBase.isMultipartContent(new PortletRequestContext(request))) {

        /*/*  w w  w .  j av a  2  s  .  c  om*/
         * Attachments may have been removed in the edit mode. We must
         * refresh the session-bound post before updating attachments.
         */
        final PortletPreferencesWrapper pref = new PortletPreferencesWrapper(request);
        final Post originalPost = getRepositoryDao().getPost(pref.getPortletRepositoryRoot());

        if (originalPost != null) {
            post.getAttachments().clear();
            post.getAttachments().addAll(originalPost.getAttachments());
        }

        final MultipartActionRequest multipartRequest = (MultipartActionRequest) request;

        for (int index = 0; index < multipartRequest.getFileMap().size(); index++) {
            final MultipartFile file = multipartRequest.getFile("attachment" + index);

            if (!file.isEmpty()) {

                logDebug("Uploading attachment file: " + file.getOriginalFilename());
                logDebug("Attachment file size: " + file.getSize());

                final Calendar cldr = Calendar.getInstance(request.getLocale());
                cldr.setTime(new Date());
                final Attachment attachment = Attachment.fromFile(file.getOriginalFilename(),
                        file.getContentType(), cldr, file.getBytes());

                final String title = multipartRequest.getParameter("attachmentTitle" + index);
                attachment.setTitle(title);
                post.getAttachments().add(attachment);
            }

        }
    }
}

From source file:com.fengduo.bee.service.impl.file.FileServiceImpl.java

public Result createFilePath(MultipartFile file, IFileCreate... ihandle) {
    // ?//from www .j  a va  2s .c o  m
    if (file == null) {
        return Result.failed();
    }
    if (!file.isEmpty()) {
        if (StringUtils.isEmpty(file.getOriginalFilename())) {
            return Result.failed();
        }
        String[] suffixArray = StringUtils.split(file.getOriginalFilename(), DELIMITER);
        if (Argument.isEmptyArray(suffixArray)) {
            return Result.failed();
        }
        String prefix = null;
        if (Argument.isEmptyArray(ihandle)) {
            prefix = Identities.uuid2();
        } else {
            prefix = ihandle[0].build(Identities.uuid2(), StringUtils.EMPTY);
        }
        String suffix = null;
        if (suffixArray.length == 1) {
            suffix = "jpg";
        } else {
            suffix = suffixArray[1];
        }
        String filePath = prefix + DELIMITER + suffix;
        // String filePath48 = prefix + "=48x48" + DELIMITER + suffix;
        try {
            File targetFile = new File(UPLOAD_TMP_PATH + filePath);
            if (targetFile != null && targetFile.getParentFile() != null
                    && !targetFile.getParentFile().exists()) {
                logger.error("?,!");
                targetFile.getParentFile().mkdirs();
            }
            // 
            file.transferTo(new File(UPLOAD_TMP_PATH + filePath));
            // FileUtils.copyFile(new File(UPLOAD_TMP_PATH + filePath), new
            // File(UPLOAD_TMP_PATH + filePath48));
            return Result.success(null, STATIC_TMP_IMG + filePath);
        } catch (Exception e) {
            logger.error(":" + e.getMessage());
            return Result.failed(":" + e.getMessage());
        }
    }
    return Result.failed();
}

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

@RequestMapping("/file/replace")
public String replace(@RequestParam Long id, @RequestParam("file") MultipartFile uploadedFile,
        ModelMap models) {// ww  w.j  av  a2 s.c  o m
    File file = fileDao.getFile(id);
    if (!file.isRegular() || file.isDeleted() || file.isFolder())
        return "redirect:/";

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

        file.setName(uploadedFile.getOriginalFilename());
        file.setType(uploadedFile.getContentType());
        file.setSize(uploadedFile.getSize());
        file.setDate(new Date());
        file = fileDao.saveFile(file);
        fileIO.save(file, uploadedFile);
    }

    return "redirect:/file/edit?id=" + id;
}