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:ua.aits.sdolyna.controller.SystemController.java

@RequestMapping(value = { "/Sdolyna/system/do/uploadimage", "/system/do/uploadimage",
        "/Sdolyna/system/do/uploadimage/", "/system/do/uploadimage/" }, method = RequestMethod.POST)
public @ResponseBody String uploadImageHandler(@RequestParam("file") MultipartFile file,
        @RequestParam("path") String path, HttpServletRequest request) {
    Integer curent = Integer.parseInt(Helpers.lastFileModified(Constants.home + path).getName().split("\\.")[0])
            + 1;/*from   w ww .  jav  a  2s . com*/
    String ext = file.getOriginalFilename().split("\\.")[1];
    String name = curent.toString() + "." + ext;
    if (!file.isEmpty()) {
        try {
            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 name;
        } 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:ua.aits.sdolyna.controller.SystemController.java

@RequestMapping(value = { "/Sdolyna/system/do/uploadfile", "/system/do/uploadfile",
        "/Sdolyna/system/do/uploadfile/", "/system/do/uploadfile/" }, method = RequestMethod.POST)
public @ResponseBody String uploadFileHandler(@RequestParam("file") MultipartFile file,
        @RequestParam("path") String path, HttpServletRequest request) {
    Integer curent = Integer.parseInt(Helpers.lastFileModified(Constants.home + path).getName().split("\\.")[0])
            + 1;// www . jav  a2s .c o m
    String ext = file.getOriginalFilename().split("\\.")[1];
    String name = curent.toString() + "." + ext;
    if (!file.isEmpty()) {
        try {
            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 name;
        } 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:ua.aits.sdolyna.controller.SystemController.java

@RequestMapping(value = { "/Sdolyna/uploadFile", "/uploadFile", "/Sdolyna/uploadFile/",
        "/uploadFile/" }, method = RequestMethod.POST)
public @ResponseBody String uploadFileHandlerFull(@RequestParam("upload") MultipartFile file,
        @RequestParam("path") String path, HttpServletRequest request) {
    Integer curent = Integer.parseInt(Helpers.lastFileModified(Constants.home + path).getName().split("\\.")[0])
            + 1;//from  w  w w. j  ava 2  s .c  o  m
    String ext = file.getOriginalFilename().split("\\.")[1];
    String name = curent.toString() + "." + ext;
    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();
            // Creating the directory to store file
            File dir = new File(Constants.home + path);
            if (!dir.exists())
                dir.mkdirs();

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
            try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) {
                stream.write(bytes);
            }
            String link_path = serverFile.getAbsolutePath().replace(Constants.home, "");
            return "<img class=\"main-img\" src=\"" + Constants.URL + link_path + "\" realpath='" + link_path
                    + "'  alt='" + link_path + file.getName() + "'  />";
        } 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:org.literacyapp.web.content.multimedia.video.VideoCreateController.java

@RequestMapping(method = RequestMethod.POST)
public String handleSubmit(HttpSession session, /*@Valid*/ Video video,
        @RequestParam("bytes") MultipartFile multipartFile, BindingResult result, Model model) {
    logger.info("handleSubmit");

    if (StringUtils.isBlank(video.getTitle())) {
        result.rejectValue("title", "NotNull");
    } else {/*from   w ww .  j av a  2s  . c  o m*/
        Video existingVideo = videoDao.read(video.getTitle(), video.getLocale());
        if (existingVideo != null) {
            result.rejectValue("title", "NonUnique");
        }
    }

    try {
        byte[] bytes = multipartFile.getBytes();
        if (multipartFile.isEmpty() || (bytes == null) || (bytes.length == 0)) {
            result.rejectValue("bytes", "NotNull");
        } else {
            String originalFileName = multipartFile.getOriginalFilename();
            logger.info("originalFileName: " + originalFileName);
            if (originalFileName.toLowerCase().endsWith(".m4v")) {
                video.setVideoFormat(VideoFormat.M4V);
            } else if (originalFileName.toLowerCase().endsWith(".mp4")) {
                video.setVideoFormat(VideoFormat.MP4);
            } else {
                result.rejectValue("bytes", "typeMismatch");
            }

            if (video.getVideoFormat() != null) {
                String contentType = multipartFile.getContentType();
                logger.info("contentType: " + contentType);
                video.setContentType(contentType);

                video.setBytes(bytes);

                // TODO: convert to a default video format?
            }
        }
    } catch (IOException e) {
        logger.error(e);
    }

    if (result.hasErrors()) {
        model.addAttribute("contentLicenses", ContentLicense.values());

        model.addAttribute("literacySkills", LiteracySkill.values());
        model.addAttribute("numeracySkills", NumeracySkill.values());

        return "content/multimedia/video/create";
    } else {
        video.setTitle(video.getTitle().toLowerCase());
        video.setTimeLastUpdate(Calendar.getInstance());
        videoDao.create(video);

        Contributor contributor = (Contributor) session.getAttribute("contributor");

        ContentCreationEvent contentCreationEvent = new ContentCreationEvent();
        contentCreationEvent.setContributor(contributor);
        contentCreationEvent.setContent(video);
        contentCreationEvent.setCalendar(Calendar.getInstance());
        contentCreationEventDao.create(contentCreationEvent);

        if (EnvironmentContextLoaderListener.env == Environment.PROD) {
            String text = URLEncoder
                    .encode(contributor.getFirstName() + " just added a new Video:\n" + " Language: "
                            + video.getLocale().getLanguage() + "\n" + " Title: \"" + video.getTitle()
                            + "\"\n" + " Video format: " + video.getVideoFormat() + "\n" + "See ")
                    + "http://literacyapp.org/content/multimedia/video/list";
            String iconUrl = contributor.getImageUrl();
            SlackApiHelper.postMessage(Team.CONTENT_CREATION, text, iconUrl, "http://literacyapp.org/video/"
                    + video.getId() + "." + video.getVideoFormat().toString().toLowerCase());
        }

        return "redirect:/content/multimedia/video/list";
    }
}

From source file:org.openmrs.module.sync.web.controller.StatusListController.java

/**
 * The onSubmit function receives the form/command object that was modified by the input form
 * and saves it to the db//from w  w w.ja  v  a 2  s.c o  m
 * 
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 */
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
        BindException errors) throws Exception {

    ModelAndView result = new ModelAndView(new RedirectView(getSuccessView()));

    // TODO - replace with privilege check
    if (!Context.isAuthenticated())
        throw new APIAuthenticationException("Not authenticated!");

    RemoteServer parent = null;
    HttpSession httpSession = request.getSession();
    String success = "";
    String error = "";
    MessageSourceAccessor msa = getMessageSourceAccessor();

    String action = ServletRequestUtils.getStringParameter(request, "action", "");

    SyncService syncService = Context.getService(SyncService.class);

    if ("resetAttempts".equals(action)) {
        List<SyncRecord> syncRecords = syncService.getSyncRecords(SyncRecordState.FAILED_AND_STOPPED);
        for (SyncRecord syncRecord : syncRecords) {
            syncRecord.setState(SyncRecordState.FAILED);
            syncRecord.setRetryCount(0);
            syncService.updateSyncRecord(syncRecord);
        }
        success = msa.getMessage("sync.status.transmission.reset.attempts.success",
                new Object[] { syncRecords.size() });
        result.addObject("mode", request.getParameter("mode"));
    } else if ("createTx".equals(action)) { // handle transmission generation
        try {
            parent = syncService.getParentServer();
            if (parent == null) {
                throw new SyncException(
                        "Could not retrieve information about the parent server; null returned.");
            }

            // we are creating a sync-transmission, so start by generating a SyncTransmission object
            // and this is a sychronization via file   due the value of action being createTx   
            SyncTransmission tx = SyncUtilTransmission.createSyncTransmission(parent, true,
                    SyncUtil.getGlobalPropetyValueAsInteger(SyncConstants.PROPERTY_NAME_MAX_RECORDS_FILE));
            String toTransmit = null; // the actual text that will be sent (either an ST or an STR)

            // Pull out the committed records from parent that haven't been sent back for confirmation
            // these are all the records we've received and are not sending a confirmation of receipt
            List<SyncImportRecord> syncImportRecords = syncService
                    .getSyncImportRecords(SyncRecordState.COMMITTED, SyncRecordState.ALREADY_COMMITTED);

            SyncTransmissionResponse str = new SyncTransmissionResponse();
            str.setState(SyncTransmissionState.OK);
            str.setSyncImportRecords(syncImportRecords);
            //note: this is transmission *response* object: as in child's response to parent
            //so the target/source is viewed from 'parent' perspective, 
            //hence for responses the target ID contains the server that generated the response
            //in this case that means: the target uuid is current server (child) uuid and source uuid is the parent 
            str.setSyncSourceUuid(tx.getSyncTargetUuid());
            str.setSyncTargetUuid(tx.getSyncSourceUuid());
            str.setSyncTransmission(tx);
            str.setTimestamp(tx.getTimestamp());
            str.setUuid(tx.getUuid());
            str.setFileName(""); //of no relevance; we're not saving to file system

            str.createFile(false);
            toTransmit = str.getFileOutput();

            // Record last attempt
            parent.setLastSync(new Date());
            syncService.saveRemoteServer(parent);

            // Write text to response
            InputStream in = new ByteArrayInputStream(toTransmit.getBytes());
            response.setContentType("text/xml; charset=utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + tx.getFileName() + ".xml");
            OutputStream out = response.getOutputStream();
            IOUtils.copy(in, out);
            out.flush();
            out.close();

            for (SyncImportRecord record : syncImportRecords) {
                record.setState(SyncRecordState.COMMITTED_AND_CONFIRMATION_SENT);
                syncService.updateSyncImportRecord(record);
            }

            // don't return a model/view - we'll need to return a file instead.
            result = null;
        } catch (Exception e) {
            e.printStackTrace();
            error = msa.getMessage("sync.status.createTx.error");
        }
    } else if ("uploadResponse".equals(action) && request instanceof MultipartHttpServletRequest) {

        try {
            String contents = "";
            parent = syncService.getParentServer();

            // first, get contents of file that is being uploaded.  it is clear we are uploading a response from parent at this point
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile multipartSyncFile = multipartRequest.getFile("syncResponseFile");
            if (multipartSyncFile != null && !multipartSyncFile.isEmpty()) {
                InputStream inputStream = null;
                StringBuilder sb = new StringBuilder();

                try {
                    inputStream = multipartSyncFile.getInputStream();
                    BufferedReader in = new BufferedReader(
                            new InputStreamReader(inputStream, SyncConstants.UTF8));
                    String line = "";
                    while ((line = in.readLine()) != null) {
                        sb.append(line);
                    }
                    contents = sb.toString();
                } catch (Exception e) {
                    log.error("Unable to read in sync data file", e);
                    error = e.getMessage();
                } finally {
                    try {
                        if (inputStream != null)
                            inputStream.close();
                    } catch (IOException io) {
                        log.error("Unable to close temporary input stream", io);
                    }
                }
            }

            if (contents.length() > 0) {
                SyncTransmissionResponse str = SyncDeserializer.xmlToSyncTransmissionResponse(contents);

                int numCommitted = 0;
                int numAlreadyCommitted = 0;
                int numFailed = 0;
                int numOther = 0;

                if (str.getSyncImportRecords() == null)
                    log.debug("No records to process in response");
                else {
                    // process each incoming syncImportRecord, this is just status update
                    for (SyncImportRecord importRecord : str.getSyncImportRecords()) {
                        Context.getService(SyncIngestService.class).processSyncImportRecord(importRecord,
                                parent);
                    }
                }

                try {
                    // store this file on filesystem too
                    str.createFile(false, SyncConstants.DIR_JOURNAL);
                } catch (Exception e) {
                    log.error("Unable to create file to store SyncTransmissionResponse: " + str.getFileName());
                    e.printStackTrace();
                }

                // now pull out the data that originated on the 'source' server and try to process it
                SyncTransmission st = str.getSyncTransmission();

                // now process the syncTransmission if one was received                    
                if (st != null) {
                    str = SyncUtilTransmission.processSyncTransmission(st, SyncUtil
                            .getGlobalPropetyValueAsInteger(SyncConstants.PROPERTY_NAME_MAX_RECORDS_FILE));
                    // get some numbers about what was just processed to show user the results
                    if (str.getSyncImportRecords() != null) {
                        for (SyncImportRecord importRecord : str.getSyncImportRecords()) {
                            if (importRecord.getState().equals(SyncRecordState.COMMITTED))
                                numCommitted++;
                            else if (importRecord.getState().equals(SyncRecordState.ALREADY_COMMITTED))
                                numAlreadyCommitted++;
                            else if (importRecord.getState().equals(SyncRecordState.FAILED))
                                numFailed++;
                            else
                                numOther++;
                        }
                    }
                }

                Object[] args = { numCommitted, numFailed, numAlreadyCommitted, numOther };

                success = msa.getMessage("sync.status.uploadResponse.success", args);
            } else {
                error = msa.getMessage("sync.status.uploadResponse.fileEmpty");
            }
        } catch (Exception e) {
            e.printStackTrace();
            error = msa.getMessage("sync.status.uploadResponse.error");
        }
    }

    if (!success.equals(""))
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, success);

    if (!error.equals(""))
        httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, error);

    return result;
}

From source file:org.kievguide.controller.UserController.java

@RequestMapping(value = "/settingssave", method = RequestMethod.POST)
public ModelAndView settingsSave(@CookieValue(value = "userstatus", defaultValue = "guest") String useremail,
        @RequestParam("firstname") String firstname, @RequestParam("lastname") String lastname,
        @RequestParam("email") String email, @RequestParam("password") String password,
        @RequestParam("photosrc") MultipartFile file, HttpServletResponse response, HttpServletRequest request)
        throws FileNotFoundException, IOException {
    ModelAndView modelAndView = new ModelAndView();
    SecureRandom random = new SecureRandom();
    String photoname = new BigInteger(130, random).toString(32);
    Place place = new Place();

    User user = userService.searchUser(useremail);
    user.setFirstname(firstname);/*ww w. j a v  a  2s.com*/
    user.setLastname(lastname);
    user.setPassword(password);
    user.setEmail(email);
    if (!file.isEmpty()) {
        String folder = request.getSession().getServletContext().getRealPath("");
        folder = folder.substring(0, 30);
        BufferedOutputStream stream = new BufferedOutputStream(
                new FileOutputStream(new File(folder + "/src/main/webapp/img/" + photoname + ".jpg")));
        FileCopyUtils.copy(file.getInputStream(), stream);
        stream.close();
        user.setPhotosrc("img/" + photoname + ".jpg");
    }

    userService.addUser(user);
    Cookie userCookie = new Cookie("userstatus", user.getEmail());
    response.addCookie(userCookie);
    String userStatus = Util.userPanel(user.getEmail());
    modelAndView.addObject("userstatus", userStatus);
    return new ModelAndView("redirect:" + "firstrequest");
}

From source file:com.rsginer.spring.controllers.RestaurantesController.java

@RequestMapping(value = { "/upload-file" }, method = RequestMethod.POST, produces = "application/json")
public void uploadFile(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        @RequestParam("file") MultipartFile file) {
    try {//from   www  . j av  a  2s. co m
        String rutaRelativa = "/uploads";
        String rutaAbsoluta = httpServletRequest.getServletContext().getVirtualServerName();
        String jsonSalida = jsonTransformer
                .toJson("http://" + rutaAbsoluta + ":" + httpServletRequest.getLocalPort()
                        + httpServletRequest.getContextPath() + "/uploads/" + file.getOriginalFilename());
        if (!file.isEmpty()) {
            int res = fileSaveService.saveFile(file, httpServletRequest);
            if (res == 200) {
                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                httpServletResponse.setContentType("application/json; charset=UTF-8");
                try {
                    httpServletResponse.getWriter().println(jsonSalida);
                } catch (IOException ex) {
                    Logger.getLogger(RestaurantesController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } else {
            httpServletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
    } catch (BussinessException ex) {
        List<BussinessMessage> bussinessMessages = ex.getBussinessMessages();
        String jsonSalida = jsonTransformer.toJson(bussinessMessages);
        httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        try {
            httpServletResponse.getWriter().println(jsonSalida);
        } catch (IOException ex1) {
            Logger.getLogger(RestaurantesController.class.getName()).log(Level.SEVERE, null, ex1);
        }
    } catch (Exception ex) {
        httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        httpServletResponse.setContentType("text/plain; charset=UTF-8");
        try {
            ex.printStackTrace(httpServletResponse.getWriter());
        } catch (IOException ex1) {
            Logger.getLogger(RestaurantesController.class.getName()).log(Level.SEVERE, null, ex1);
        }

    }

}

From source file:org.literacyapp.web.content.multimedia.audio.AudioCreateController.java

@RequestMapping(method = RequestMethod.POST)
public String handleSubmit(HttpSession session, /*@Valid*/ Audio audio,
        @RequestParam("bytes") MultipartFile multipartFile, BindingResult result, Model model) {
    logger.info("handleSubmit");

    if (StringUtils.isBlank(audio.getTranscription())) {
        result.rejectValue("transcription", "NotNull");
    } else {//  w ww  .j  a v a 2s. com
        Audio existingAudio = audioDao.read(audio.getTranscription(), audio.getLocale());
        if (existingAudio != null) {
            result.rejectValue("transcription", "NonUnique");
        }
    }

    try {
        byte[] bytes = multipartFile.getBytes();
        if (multipartFile.isEmpty() || (bytes == null) || (bytes.length == 0)) {
            result.rejectValue("bytes", "NotNull");
        } else {
            String originalFileName = multipartFile.getOriginalFilename();
            logger.info("originalFileName: " + originalFileName);
            if (originalFileName.toLowerCase().endsWith(".mp3")) {
                audio.setAudioFormat(AudioFormat.MP3);
            } else if (originalFileName.toLowerCase().endsWith(".ogg")) {
                audio.setAudioFormat(AudioFormat.OGG);
            } else if (originalFileName.toLowerCase().endsWith(".wav")) {
                audio.setAudioFormat(AudioFormat.WAV);
            } else {
                result.rejectValue("bytes", "typeMismatch");
            }

            if (audio.getAudioFormat() != null) {
                String contentType = multipartFile.getContentType();
                logger.info("contentType: " + contentType);
                audio.setContentType(contentType);

                audio.setBytes(bytes);

                // TODO: convert to a default audio format?
            }
        }
    } catch (IOException e) {
        logger.error(e);
    }

    if (result.hasErrors()) {
        model.addAttribute("contentLicenses", ContentLicense.values());

        model.addAttribute("literacySkills", LiteracySkill.values());
        model.addAttribute("numeracySkills", NumeracySkill.values());

        return "content/multimedia/audio/create";
    } else {
        audio.setTranscription(audio.getTranscription().toLowerCase());
        audio.setTimeLastUpdate(Calendar.getInstance());
        audioDao.create(audio);

        Contributor contributor = (Contributor) session.getAttribute("contributor");

        ContentCreationEvent contentCreationEvent = new ContentCreationEvent();
        contentCreationEvent.setContributor(contributor);
        contentCreationEvent.setContent(audio);
        contentCreationEvent.setCalendar(Calendar.getInstance());
        contentCreationEventDao.create(contentCreationEvent);

        if (EnvironmentContextLoaderListener.env == Environment.PROD) {
            String text = URLEncoder.encode(contributor.getFirstName() + " just added a new Audio:\n"
                    + " Language: " + audio.getLocale().getLanguage() + "\n" + " Transcription: \""
                    + audio.getTranscription() + "\"\n" + " Audio format: " + audio.getAudioFormat() + "\n"
                    + "See ") + "http://literacyapp.org/content/multimedia/audio/list";
            String iconUrl = contributor.getImageUrl();
            SlackApiHelper.postMessage(Team.CONTENT_CREATION, text, iconUrl, "http://literacyapp.org/audio/"
                    + audio.getId() + "." + audio.getAudioFormat().toString().toLowerCase());
        }

        return "redirect:/content/multimedia/audio/list";
    }
}

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

@RequestMapping(value = "/site/{qtr}/{cc}-{sn}/block/editResource", method = RequestMethod.POST)
public String editResource(@ModelAttribute Item item, @ModelAttribute Resource resource,
        @RequestParam Long blockId,
        @RequestParam(value = "uploadedFile", required = false) MultipartFile uploadedFile,
        BindingResult bindingResult, SessionStatus sessionStatus) {
    resourceValidator.validate(resource, uploadedFile, bindingResult);
    if (bindingResult.hasErrors())
        return "site/block/editResource";

    User user = SecurityUtils.getUser();
    if (resource.getType() == ResourceType.FILE && uploadedFile != null && !uploadedFile.isEmpty())
        resource.setFile(fileIO.save(uploadedFile, user, true));
    item = itemDao.saveItem(item);/*from  ww  w.  j  ava 2  s  . co  m*/
    logger.info(user.getUsername() + " edited a resource of item " + item.getId() + " in block " + blockId);
    sessionStatus.setComplete();

    return "redirect:editItem?blockId=" + blockId + "&itemId=" + item.getId();
}