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.mycompany.projetsportmanager.spring.rest.controllers.UserController.java

/**
 * Affect a image to a specified user/*from w w w .ja  v  a 2  s  . c o  m*/
 * 
 * @param userId
 *            the user identifier
 * @param uploadedInputStream
 *            the image uploaded input stream
 * @param fileDetail
 *            the image detail format
 * @return response
 */
@RequestMapping(method = RequestMethod.POST, value = "/{userId}/picture")
@ResponseStatus(HttpStatus.OK)
@PreAuthorize(value = "hasRole('AK_ADMIN')")
public void pictureUpdate(@PathVariable("userId") Long userId, @RequestParam MultipartFile user_picture) {

    //Le nom du paramtre correspond au nom du champ de formulaire qu'il faut utiliser !!!!

    if (user_picture == null || user_picture.isEmpty()) {
        logger.debug("Incorrect input stream or file name for image of user" + userId);
        throw new DefaultSportManagerException(new ErrorResource("parameter missing",
                "Picture should be uploaded as a multipart/form-data file param named user_picture",
                HttpStatus.BAD_REQUEST));
    }

    if (!(user_picture.getOriginalFilename().endsWith(".jpg")
            || user_picture.getOriginalFilename().endsWith(".jpeg"))) {
        logger.debug("File for picture of user" + userId + " must be a JPEG file.");
        throw new DefaultSportManagerException(new ErrorResource("incorrect file format",
                "Picture should be a JPG file", HttpStatus.BAD_REQUEST));
    }

    try {
        userService.addUserPicture(userId, user_picture.getInputStream());
    } catch (SportManagerException e) {
        String msg = "Can't update user picture with id " + userId + " into DB";
        logger.error(msg, e);
        throw new DefaultSportManagerException(
                new ErrorResource("db error", msg, HttpStatus.INTERNAL_SERVER_ERROR));
    } catch (IOException e) {
        String msg = "Can't update user picture with id " + userId + " because of IO Error";
        logger.error(msg, e);
        throw new DefaultSportManagerException(
                new ErrorResource("io error", msg, HttpStatus.INTERNAL_SERVER_ERROR));
    }
}

From source file:com.peadargrant.filecheck.web.controllers.CheckController.java

@RequestMapping(method = RequestMethod.POST)
public String performCheck(@RequestParam(value = "assignment", required = true) String assignmentCode,
        @RequestParam("file") MultipartFile file, ModelMap model) throws Exception {

    String assignmentsUrl = serverEnvironment.getPropertyAsString("assignmentsUrl");
    model.addAttribute("assignmentsUrl", assignmentsUrl);

    // bail out if the file is empty
    if (file.isEmpty()) {
        model.addAttribute("message", "file.was.empty");
        return "error";
    }/*ww  w .  j  a v a 2s. co  m*/

    // input stream from file 
    byte[] bytes = file.getBytes();
    String name = file.getOriginalFilename();

    // write to temp dir
    String filePath = System.getProperty("java.io.tmpdir") + "/" + name;
    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
    stream.write(bytes);
    stream.close();

    // load file
    File inputFile = new File(filePath);

    // get assignment
    Assignment assignment = this.getAssignmentForCode(assignmentCode);
    if (assignment == null) {
        return "assignmentNotFound";
    }
    model.addAttribute(assignment);

    // GUI report table model
    SummaryTableModel summaryTableModel = new SummaryTableModel();
    ReportTableModel reportTableModel = new ReportTableModel(summaryTableModel);

    // checker
    Checker checker = new Checker();
    checker.setReport(reportTableModel);
    checker.runChecks(inputFile, assignment);

    // details for output
    model.addAttribute("fileName", name);
    model.addAttribute("startTime", new java.util.Date());
    String ipAddress = request.getHeader("X-FORWARDED-FOR");
    if (ipAddress == null) {
        ipAddress = request.getRemoteAddr();
    }
    model.addAttribute("remoteIP", ipAddress);

    // final outcome
    model.addAttribute("outcome", summaryTableModel.getFinalOutcome());
    Color finalOutcomeColor = summaryTableModel.getFinalOutcome().getSaturatedColor();
    model.addAttribute("colourr", finalOutcomeColor.getRed());
    model.addAttribute("colourg", finalOutcomeColor.getGreen());
    model.addAttribute("colourb", finalOutcomeColor.getBlue());

    // transformer for parsing tables
    FileCheckWebTableTransformer transformer = new FileCheckWebTableTransformer();

    // summary table headings
    List<String> summaryColumns = transformer.getColumnHeaders(summaryTableModel);
    model.addAttribute("summaryColumns", summaryColumns);

    // summary table
    List summaryContents = transformer.getTableContents(summaryTableModel);
    model.addAttribute("summary", summaryContents);

    // detail table headings
    List<String> detailColumns = transformer.getColumnHeaders(reportTableModel);
    model.addAttribute("detailColumns", detailColumns);

    // detail report table
    List detailContents = transformer.getTableContents(reportTableModel);
    model.addAttribute("detail", detailContents);

    // delete the uploaded file
    inputFile.delete();

    // Return results display
    return "check";
}

From source file:com.fh.controller.upload.FileUploadController.java

/**
 * /*from w w  w  .  j av a 2 s .  c om*/
 * 
 * @param request
 * @param name
 * @param file
 * @return
 */
@RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
public ModelAndView handleFormUpload(HttpServletRequest request, @RequestParam("name") String name,
        @RequestParam("file") MultipartFile file) throws Exception {

    pd = this.getPageData();

    String pictureSaveFilePath = PathUtil.getPicturePath("save", "business/businessLicense");
    String pictureVisitFilePath = PathUtil.getPicturePath("visit", "business/businessLicense");

    if (!file.isEmpty()) {
        try {
            String id = UuidUtil.get32UUID();
            this.copyFile(file.getInputStream(), pictureSaveFilePath, id + ".jpg").replaceAll("-", "");

            String path = pictureVisitFilePath + id + ".jpg";
            pd.put("id", id);
            pd.put("path", path);
            pd.put("type", 001);
            pd.put("picture_id", 100);
            pd.put("explanation", "");

            fileUploadService.saveFile(pd);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }
    String pathaddress = PathUtil.PathAddress();
    pd.get(pathaddress + "path");
    pd.put("path", pathaddress + pd.get("path"));

    mv.setViewName("uploadfile/success");
    mv.addObject("pd", pd);

    return mv;
}

From source file:com.trenako.web.controllers.admin.AdminRailwaysController.java

/**
 * It creates a new {@code Railway} using the posted form values.
 * <p/>/*from w  ww.ja  v a 2  s.  c  o m*/
 * <p>
 * <pre><blockquote>
 * {@code POST /admin/railways}
 * </blockquote></pre>
 * </p>
 *
 * @param railwayForm   the form for the {@code Railway} to be added
 * @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 RailwayForm railwayForm, BindingResult bindingResult,
        ModelMap model, RedirectAttributes redirectAtts) throws IOException {

    if (bindingResult.hasErrors()) {
        LogUtils.logValidationErrors(log, bindingResult);
        model.addAttribute(railwayForm);
        return "railway/new";
    }

    Railway railway = railwayForm.getRailway();
    MultipartFile file = railwayForm.getFile();
    try {
        service.save(railway);
        if (file != null && !file.isEmpty()) {
            imgService.saveImageWithThumb(UploadRequest.create(railway, file), 50);
        }

        RAILWAY_CREATED_MSG.appendToRedirect(redirectAtts);
        return "redirect:/admin/railways";
    } catch (DuplicateKeyException dke) {
        LogUtils.logException(log, dke);
        bindingResult.rejectValue("railway.name", "railway.name.already.used");
    } catch (DataAccessException dae) {
        LogUtils.logException(log, dae);
        RAILWAY_DB_ERROR_MSG.appendToModel(model);
    }

    model.addAttribute(railwayForm);
    return "railway/new";
}

From source file:org.openmrs.module.owa.web.controller.OwaRestController.java

@RequestMapping(value = "/rest/owa/addapp", method = RequestMethod.POST)
@ResponseBody/*  w w w . j  a va2 s .  co m*/
public List<App> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    List<App> appList = new ArrayList<>();
    if (Context.hasPrivilege("Manage OWA")) {
        String message;
        HttpSession session = request.getSession();
        if (!file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            File uploadedFile = new File(file.getOriginalFilename());
            file.transferTo(uploadedFile);
            try (ZipFile zip = new ZipFile(uploadedFile)) {
                if (zip.size() == 0) {
                    message = messageSourceService.getMessage("owa.blank_zip");
                    log.warn("Zip file is empty");
                    session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, message);
                    response.sendError(500, message);
                } else {
                    ZipEntry entry = zip.getEntry("manifest.webapp");
                    if (entry == null) {
                        message = messageSourceService.getMessage("owa.manifest_not_found");
                        log.warn("Manifest file could not be found in app");
                        uploadedFile.delete();
                        session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, message);
                        response.sendError(500, message);
                    } else {
                        String contextPath = request.getScheme() + "://" + request.getServerName() + ":"
                                + request.getServerPort() + request.getContextPath();
                        appManager.installApp(uploadedFile, fileName, contextPath);
                        message = messageSourceService.getMessage("owa.app_installed");
                        session.setAttribute(WebConstants.OPENMRS_MSG_ATTR, message);
                    }
                }
            } catch (Exception e) {
                message = messageSourceService.getMessage("owa.not_a_zip");
                log.warn("App is not a zip archive");
                uploadedFile.delete();
                session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, message);
                response.sendError(500, message);
            }
        }
        appManager.reloadApps();
        appList = appManager.getApps();
    }
    return appList;
}

From source file:ua.aits.crc.controller.SystemController.java

@RequestMapping(value = { "/system/do/uploadimage", "/system/do/uploadimage/" }, method = RequestMethod.POST)
public @ResponseBody String uploadImageHandler(@RequestParam("file") MultipartFile file,
        @RequestParam("path") String path, HttpServletRequest request) {
    String name = file.getOriginalFilename();
    name = TransliteratorClass.transliterate(name);
    if (!file.isEmpty()) {
        try {//ww  w  . ja  va 2  s  . c o  m
            byte[] bytes = file.getBytes();
            File dir = new File(Constants.home + path);
            if (!dir.exists())
                dir.mkdirs();
            File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
            try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) {
                stream.write(bytes);
            }
            return "";
        } catch (Exception e) {
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + name + " because the file was empty.";
    }
}

From source file:com.daphne.es.maintain.icon.web.controller.IconController.java

@RequestMapping(value = "{id}/update", method = RequestMethod.POST)
public String update(HttpServletRequest request, Model model,
        @RequestParam(value = "file", required = false) MultipartFile file,
        @Valid @ModelAttribute("m") Icon icon, BindingResult result,
        @RequestParam(value = "BackURL") String backURL, RedirectAttributes redirectAttributes) {
    if (file != null && !file.isEmpty()) {
        icon.setImgSrc(FileUploadUtils.upload(request, file, result));
    }/*from  w w  w.  ja v  a  2s. c  o  m*/
    String view = super.update(model, icon, result, backURL, redirectAttributes);
    genIconCssFile(request);
    return view;
}

From source file:org.openmrs.module.dhisconnector.web.controller.DHISConnectorController.java

@RequestMapping(value = "/module/dhisconnector/uploadMapping", method = RequestMethod.POST)
public void uploadMapping(ModelMap model,
        @RequestParam(value = "mapping", required = false) MultipartFile mapping) {
    String successMessage = "";
    String failedMessage = "";

    if (!mapping.isEmpty()) {
        String msg = Context.getService(DHISConnectorService.class).uploadMappings(mapping);

        if (msg.startsWith("Successfully")) {
            successMessage = msg;/* ww w. j  a  va  2s.  co  m*/
            failedMessage = "";
        } else {
            failedMessage = msg;
            successMessage = "";
        }
    } else {
        failedMessage = Context.getMessageSourceService()
                .getMessage("dhisconnector.uploadMapping.mustSelectFile");
    }
    passOnUploadingFeedback(model, successMessage, failedMessage);
}

From source file:ca.intelliware.ihtsdo.mlds.web.rest.MemberResource.java

@RequestMapping(value = Routes.MEMBER_LICENSE, method = RequestMethod.POST, headers = "content-type=multipart/*", produces = "application/json")
@RolesAllowed({ AuthoritiesConstants.STAFF, AuthoritiesConstants.ADMIN })
@Transactional//from w  w  w  .  j av  a 2 s . co  m
@Timed
public ResponseEntity<?> updateMemberLicense(@PathVariable String memberKey,
        @RequestParam(value = "file", required = false) MultipartFile multipartFile,
        @RequestParam("licenseName") String licenseName, @RequestParam("licenseVersion") String licenseVersion)
        throws IOException {
    Member member = memberRepository.findOneByKey(memberKey);

    if (multipartFile != null && !multipartFile.isEmpty()) {
        File licenseFile = updateFile(multipartFile, member.getLicense());
        member.setLicense(licenseFile);
    }

    member.setLicenseName(licenseName);
    member.setLicenseVersion(licenseVersion);

    memberRepository.save(member);

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

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

public Result createFilePath(MultipartFile file, String filePath) {
    if (file == null || StringUtils.isEmpty(filePath)) {
        return Result.failed();
    }/* w ww .  j a  v  a 2  s.  c  om*/
    if (!file.isEmpty()) {
        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();
}