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.trenako.web.controllers.admin.AdminBrandsController.java

/**
 * It creates a new {@code Brand} using the posted form values.
 * <p/>/*from   w  w  w  . ja  va2  s .co m*/
 * <p>
 * <pre><blockquote>
 * {@code POST /brands}
 * </blockquote></pre>
 * </p>
 *
 * @param form          the form for {@code Brand} to be created
 * @param bindingResult the validation results
 * @param model         the model
 * @param redirectAtts  the redirect attributes
 * @return the view name
 * @throws IOException
 */
@RequestMapping(method = RequestMethod.POST)
public String create(@Valid @ModelAttribute BrandForm form, BindingResult bindingResult, ModelMap model,
        RedirectAttributes redirectAtts) throws IOException {

    if (bindingResult.hasErrors()) {
        LogUtils.logValidationErrors(log, bindingResult);
        model.addAttribute(BrandForm.rejectedForm(form, formService));
        return "brand/new";
    }

    Brand brand = form.getBrand();
    MultipartFile file = form.getFile();
    try {
        service.save(brand);
        if (!file.isEmpty()) {
            imgService.saveImageWithThumb(UploadRequest.create(brand, file), 50);
        }

        BRAND_CREATED_MSG.appendToRedirect(redirectAtts);
        return "redirect:/admin/brands";
    } catch (DuplicateKeyException dke) {
        LogUtils.logException(log, dke);
        bindingResult.rejectValue("brand.name", "brand.name.already.used");
    } catch (DataAccessException dae) {
        LogUtils.logException(log, dae);
        BRAND_DB_ERROR_MSG.appendToModel(model);
    }

    model.addAttribute(BrandForm.rejectedForm(form, formService));
    return "brand/new";
}

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

@RequestMapping(value = "/course/edit", method = RequestMethod.POST)
public String edit(@ModelAttribute Course course,
        @RequestParam(value = "file", required = false) MultipartFile uploadedFile, BindingResult bindingResult,
        SessionStatus sessionStatus) {/*from  w w  w .  j  a v  a 2 s. co m*/
    courseValidator.validate(course, bindingResult);
    if (bindingResult.hasErrors())
        return "course/edit";

    if (uploadedFile != null && !uploadedFile.isEmpty())
        course.setDescription(fileIO.save(uploadedFile, SecurityUtils.getUser(), true));

    course.setDepartment(departmentDao.getDepartment(course.getDept()));
    course = courseDao.saveCourse(course);

    Forum forum = forumDao.getForum(course);
    forum.setName(course.getCode() + " " + course.getName());
    forumDao.saveForum(forum);

    logger.info(SecurityUtils.getUser().getUsername() + " edited course " + course.getId());

    sessionStatus.setComplete();
    return "redirect:view?id=" + course.getId();
}

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

@RequestMapping(value = "/course/create", method = RequestMethod.POST)
public String create(@ModelAttribute Course course,
        @RequestParam(value = "file", required = false) MultipartFile uploadedFile, BindingResult bindingResult,
        SessionStatus sessionStatus) {//from ww w .  j a  v  a  2  s . c o m
    courseValidator.validate(course, bindingResult);
    if (bindingResult.hasErrors())
        return "course/create";

    if (uploadedFile != null && !uploadedFile.isEmpty())
        course.setDescription(fileIO.save(uploadedFile, SecurityUtils.getUser(), true));

    course.setDepartment(departmentDao.getDepartment(course.getDept()));
    course = courseDao.saveCourse(course);

    Forum forum = new Forum(course.getCode() + " " + course.getName());
    forum.setCourse(course);
    forumDao.saveForum(forum);

    logger.info(SecurityUtils.getUser().getUsername() + " created course " + course.getId());

    sessionStatus.setComplete();
    return "redirect:view?id=" + course.getId();
}

From source file:com.card.loop.xyz.controller.LearningObjectController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(@RequestParam(value = "title") String title, @RequestParam("author") String author,
        @RequestParam("description") String description, @RequestParam("file") MultipartFile file,
        @RequestParam("type") String type) {
    if (!file.isEmpty()) {
        try {/*  w  w  w  .j  a  v  a  2  s  . c o  m*/
            byte[] bytes = file.getBytes();
            File fil = new File(AppConfig.UPLOAD_BASE_PATH + file.getOriginalFilename());
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fil));
            stream.write(bytes);
            stream.close();

            LearningObject lo = new LearningObject();
            System.out.println(title);
            System.out.println(author);
            System.out.println(description);

            lo.setTitle(title);
            lo.setUploadedBy(author);
            lo.setDateUpload(new Date());
            lo.setDescription(description);
            lo.setStatus(0);
            lo.setDownloads(0);
            lo.setRating(1);

            System.out.println("UPLOAD LO FINISHED");

        } catch (Exception e) {
            System.err.println(e.toString());
        }
    } else {
        System.err.println("EMPTY FILE.");
    }

    return "redirect:/developer-update";
}

From source file:org.trpr.platform.batch.impl.spring.web.JobConfigController.java

/**
 * Controller for new job. Just adds an attribute jobName to the model. And redirects to the job edit page.
 *//*  w  ww . java2  s. c o m*/
@RequestMapping(value = "/configuration/modify_job", method = RequestMethod.POST)
public String addNewJob(ModelMap model, @RequestParam MultipartFile jobFile) {
    String jobFileName = jobFile.getOriginalFilename();
    //Check if file is empty or doesn't have an extension
    if (jobFile.isEmpty() || (jobFileName.lastIndexOf('.') < 0)) {
        model.remove("jobFile");
        model.addAttribute("Error", "File is Empty or invalid. Only .xml files can be uploaded");
        return "redirect:/configuration";
    } else if (!jobFileName.substring(jobFileName.lastIndexOf('.')).equals(".xml")) { //Check if file is .xml
        model.remove("jobFile");
        model.addAttribute("Error", "Only .xml files can be uploaded");
        return "redirect:/configuration";
    } else { //Read file to view
        boolean invalidJobFile = false;
        List<String> jobNameList = null;
        try {
            byte[] buffer = jobFile.getBytes();
            String XMLFileContents = new String(buffer);
            model.addAttribute("XMLFileContents", XMLFileContents);
            jobNameList = ConfigFileUtils.getJobName(new ByteArrayResource(jobFile.getBytes()));
            if (jobNameList == null || jobNameList.size() == 0) {
                throw new PlatformException("Empty list");
            }
        } catch (UnsupportedEncodingException e) {
            invalidJobFile = true;
        } catch (IOException e) {
            invalidJobFile = true;
        } catch (PlatformException p) {
            invalidJobFile = true;
        }
        for (String jobName : jobNameList) {
            if (jobName == null || invalidJobFile) {
                model.clear();
                model.addAttribute("Error", "invalid jobFile. Couldn't find job's name");
                return "redirect:/configuration";
            }
            if (jobService.contains(jobName)) {
                model.clear();
                model.addAttribute("Error",
                        "The JobName '" + jobName + "' already exists. Please choose another name");
                return "redirect:/configuration";
            }
        }
        model.addAttribute("jobName", jobNameList);
        return "configuration/modify/jobs/job";
    }
}

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

@RequestMapping(value = "/department/{dept}/project/resource/edit", method = RequestMethod.POST)
public String edit(@ModelAttribute Resource resource, @PathVariable String dept, @RequestParam Long projectId,
        @RequestParam(required = false) MultipartFile uploadedFile, BindingResult result,
        SessionStatus sessionStatus) {// ww w  . j a  v  a  2  s  .c o  m
    resourceValidator.validate(resource, uploadedFile, result);
    if (result.hasErrors())
        return "project/resource/edit";

    if (resource.getType() == ResourceType.FILE && uploadedFile != null && !uploadedFile.isEmpty())
        resource.setFile(fileIO.save(uploadedFile, SecurityUtils.getUser(), false));

    Project project = projectDao.getProject(projectId);
    project.replaceResource(resource);
    projectDao.saveProject(project);

    logger.info(SecurityUtils.getUser().getUsername() + " edited resource " + resource.getId() + " of project "
            + project.getId());

    sessionStatus.setComplete();
    return "redirect:/department/" + dept + "/project/view?id=" + projectId;
}

From source file:com.groupon.odo.controllers.BackupController.java

/**
 * Set client server configuration and overrides according to backup
 *
 * @param fileData File containing profile overrides and server configuration
 * @param profileID Profile to update for client
 * @param clientUUID Client to apply overrides to
 * @param odoImport Param to determine if an odo config will be imported with the overrides import
 * @return// ww  w  .  java2s .co m
 * @throws Exception
 */
@RequestMapping(value = "/api/backup/profile/{profileID}/{clientUUID}", method = RequestMethod.POST)
public @ResponseBody ResponseEntity<String> processSingleProfileBackup(
        @RequestParam("fileData") MultipartFile fileData, @PathVariable int profileID,
        @PathVariable String clientUUID,
        @RequestParam(value = "odoImport", defaultValue = "false") boolean odoImport) throws Exception {
    if (!fileData.isEmpty()) {
        try {
            // Read in file
            InputStream inputStream = fileData.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String singleLine;
            String fullFileString = "";
            while ((singleLine = bufferedReader.readLine()) != null) {
                fullFileString += singleLine;
            }
            JSONObject fileBackup = new JSONObject(fullFileString);

            if (odoImport) {
                JSONObject odoBackup = fileBackup.getJSONObject("odoBackup");
                byte[] bytes = odoBackup.toString().getBytes();
                // Save to second file to be used in importing odo configuration
                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(new File("backup-uploaded.json")));
                stream.write(bytes);
                stream.close();
                File f = new File("backup-uploaded.json");
                BackupService.getInstance().restoreBackupData(new FileInputStream(f));
            }

            // Get profile backup if json contained both profile backup and odo backup
            if (fileBackup.has("profileBackup")) {
                fileBackup = fileBackup.getJSONObject("profileBackup");
            }

            // Import profile overrides
            BackupService.getInstance().setProfileFromBackup(fileBackup, profileID, clientUUID);
        } catch (Exception e) {
            try {
                JSONArray errorArray = new JSONArray(e.getMessage());
                return new ResponseEntity<>(errorArray.toString(), HttpStatus.BAD_REQUEST);
            } catch (Exception k) {
                // Catch for exceptions other than ones defined in backup service
                return new ResponseEntity<>("[{\"error\" : \"Upload Error\"}]", HttpStatus.BAD_REQUEST);
            }
        }
    }

    return new ResponseEntity<>(HttpStatus.OK);
}

From source file:edu.uiowa.icts.bluebutton.controller.ClinicalDocumentController.java

@RequestMapping(value = "save.html", method = RequestMethod.POST)
public String save(@RequestParam("person.personId") Integer person_personId,
        @Valid @ModelAttribute("clinicalDocument") ClinicalDocument clinicalDocument, BindingResult result, // must immediately follow bound object
        @RequestParam("file") MultipartFile document, Model model) throws IOException {
    if (document.isEmpty()) {
        result.addError(new FieldError("clinicalDocument", "document", "may not be empty"));
    }//from  w w w  . j a  v  a 2  s .c  om
    if (result.hasErrors()) {
        model.addAttribute("personList", bluebuttonDaoService.getPersonService().list());
        return "/bluebutton/clinicaldocument/edit";
    } else {
        clinicalDocument.setPerson(bluebuttonDaoService.getPersonService().findById(person_personId));
        clinicalDocument.setDocument(document.getBytes());
        clinicalDocument.setName(document.getOriginalFilename());
        clinicalDocument.setDateUploaded(new Date());
        bluebuttonDaoService.getClinicalDocumentService().saveOrUpdate(clinicalDocument);
        return "redirect:/clinicaldocument/confirm?clinicalDocumentId="
                + clinicalDocument.getClinicalDocumentId();
    }
}

From source file:com.dpillay.projects.yafu.controller.FileUploadController.java

@RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)/* w  w w  . j  a  va 2s  . com*/
public String handleFormUpload(@RequestParam(value = "file", required = false) final MultipartFile file,
        @RequestParam(value = "key", required = false) final String key, ModelMap modelMap,
        final HttpServletRequest request) {
    if (log.isDebugEnabled())
        log.debug("Received upload file: {} with key: {}", file.getOriginalFilename(), key);
    if (!file.isEmpty()) {
        try {
            getFileUploadStatus(key, file, request.getSession().getId());
        } catch (IOException e) {
            log.error(e.getLocalizedMessage(), e);
        }
    }
    return null;
}

From source file:seava.j4e.web.controller.upload.FileUploadController.java

/**
 * Generic file upload. Expects an uploaded file and a handler alias to
 * delegate the uploaded file processing.
 * /*from  ww w  .j  ava  2 s .  co  m*/
 * @param handler
 *            spring bean alias of the
 *            {@link seava.j4e.api.service.IFileUploadService} which should
 *            process the uploaded file
 * @param file
 *            Uploaded file
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/{handler}", method = RequestMethod.POST)
@ResponseBody
public String fileUpload(@PathVariable("handler") String handler, @RequestParam("file") MultipartFile file,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    try {
        if (logger.isInfoEnabled()) {
            logger.info("Processing file upload request with-handler {} ", new Object[] { handler });
        }

        if (file.isEmpty()) {
            throw new BusinessException(ErrorCode.G_FILE_NOT_UPLOADED,
                    "Upload was not succesful. Try again please.");
        }

        this.prepareRequest(request, response);

        IFileUploadService srv = this.getFileUploadService(handler);
        Map<String, String> paramValues = new HashMap<String, String>();

        for (String p : srv.getParamNames()) {
            paramValues.put(p, request.getParameter(p));
        }

        IUploadedFileDescriptor fileDescriptor = new UploadedFileDescriptor();
        fileDescriptor.setContentType(file.getContentType());
        fileDescriptor.setOriginalName(file.getOriginalFilename());
        fileDescriptor.setNewName(file.getName());
        fileDescriptor.setSize(file.getSize());
        Map<String, Object> result = srv.execute(fileDescriptor, file.getInputStream(), paramValues);

        result.put("success", true);
        ObjectMapper mapper = getJsonMapper();
        return mapper.writeValueAsString(result);
    } catch (Exception e) {
        return this.handleManagedException(null, e, response);
    } finally {
        this.finishRequest();
    }

}