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:csns.web.controller.ResourceControllerS.java

private Resource save(Resource resource, MultipartFile uploadedFile, SessionStatus sessionStatus) {
    User user = SecurityUtils.getUser();
    if (resource.getType() == ResourceType.FILE && uploadedFile != null && !uploadedFile.isEmpty()) {
        File file = fileIO.save(uploadedFile, user, true);
        resource.setFile(file);//from  www  .ja v a  2 s  .com
    }
    resource = resourceDao.saveResource(resource);
    sessionStatus.setComplete();

    logger.info(user.getUsername() + " added/edited resource " + resource.getId());

    return resource;
}

From source file:csns.web.validator.ItemValidator.java

/**
 * Controllers should call this method instead of validate(Object,Errors) so
 * the file field can be validated as well.
 *///from  www.  j a  v  a2  s.c o  m
public void validate(Item item, MultipartFile uploadedFile, Errors errors) {
    validate(item, errors);

    Resource resource = item.getResource();
    if (resource.getType() == ResourceType.FILE && resource.getFile() == null
            && (uploadedFile == null || uploadedFile.isEmpty()))
        errors.rejectValue("resource.file", "error.field.required");
}

From source file:ru.mystamps.web.validation.jsr303.ImageFileValidator.java

@Override
@SuppressWarnings("PMD.CyclomaticComplexity")
public boolean isValid(MultipartFile file, ConstraintValidatorContext ctx) {

    if (file == null) {
        return true;
    }/*from  w  ww .  j a va  2s  .c o m*/

    if (file.isEmpty()) {
        return false;
    }

    String contentType = file.getContentType();
    if (!PNG_CONTENT_TYPE.equals(contentType) && !JPEG_CONTENT_TYPE.equals(file.getContentType())) {
        LOG.debug("Reject file with content type '{}'", contentType);
        return false;
    }

    try (InputStream stream = file.getInputStream()) {

        byte[] firstPart = readFourBytes(stream);
        if (firstPart == null) {
            LOG.warn("Failed to read 4 bytes from file");
            return false;
        }

        if (isJpeg(firstPart)) {
            return true;
        }

        if (doesItLookLikePng(firstPart)) {
            byte[] secondPart = readFourBytes(stream);
            if (isItReallyPng(secondPart)) {
                return true;
            }

            LOG.debug("Looks like file isn't a PNG image. First bytes: {} {}", formatBytes(firstPart),
                    formatBytes(secondPart));
            return false;
        }

        LOG.debug("Looks like file isn't an image. First bytes: {}", formatBytes(firstPart));
        return false;

    } catch (IOException e) {
        LOG.warn("Error during file type validation: {}", e.getMessage());
        return false;
    }
}

From source file:com.pubkit.web.controller.FileUploadController.java

@RequestMapping(value = "/upload_cert", method = RequestMethod.POST)
public @ResponseBody UploadResponse handleFileUpload(@RequestParam("applicationId") String applicationId,
        @RequestParam("fileType") String fileType, @RequestParam("file") MultipartFile multipartFile) {

    LOG.debug("Upload request received for file size:" + multipartFile.getSize());
    validateAccessToken();//from   w  ww . j  a v  a2s.  c o m

    if (multipartFile != null && !multipartFile.isEmpty()) {
        String fileName = multipartFile.getOriginalFilename();
        try {
            if (TYPE_CERT.equalsIgnoreCase(fileType)) {
                if (!".p12".endsWith(multipartFile.getOriginalFilename())
                        || !".cert".endsWith(multipartFile.getOriginalFilename())) {
                    LOG.debug("Invalid file upload type received");

                    return new UploadResponse("Invalid file type");
                }
            }
            byte[] fileData = multipartFile.getBytes();
            String uploadId = applicationService.saveFile(fileData, fileName, multipartFile.getContentType());
            if (uploadId != null) {
                return new UploadResponse(uploadId, false, null);
            }

            return new UploadResponse("Failed to upload " + fileName);
        } catch (Exception e) {
            LOG.error("Error uploading file", e);
            return new UploadResponse("Failed to upload " + fileName);
        }
    } else {
        LOG.error("Error uploading file");
        return new UploadResponse("Failed to upload");
    }
}

From source file:com.aerospike.client.rest.RESTController.java

@RequestMapping(value = "/uploadFlights", method = RequestMethod.POST)
public @ResponseBody String handleFileUpload(@RequestParam("name") String name,
        @RequestParam("file") MultipartFile file) {

    if (!file.isEmpty()) {
        try {/*from   ww  w  . j ava 2  s  .c o m*/
            WritePolicy wp = new WritePolicy();
            String line = "";
            BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream()));
            while ((line = br.readLine()) != null) {

                // use comma as separator
                String[] flight = line.split(",");

                /*
                 * write the record to Aerospike
                 * NOTE: Bin names must not exceed 14 characters
                 */
                client.put(wp, new Key("test", "flights", flight[0].trim()),
                        new Bin("YEAR", Integer.parseInt(flight[1].trim())),
                        new Bin("DAY_OF_MONTH", Integer.parseInt(flight[2].trim())),
                        new Bin("FL_DATE", flight[3].trim()),
                        new Bin("AIRLINE_ID", Integer.parseInt(flight[4].trim())),
                        new Bin("CARRIER", flight[5].trim()),
                        new Bin("FL_NUM", Integer.parseInt(flight[6].trim())),
                        new Bin("ORI_AIRPORT_ID", Integer.parseInt(flight[7].trim())),
                        new Bin("ORIGIN", flight[8].trim()), new Bin("ORI_CITY_NAME", flight[9].trim()),
                        new Bin("ORI_STATE_ABR", flight[10].trim()), new Bin("DEST", flight[11].trim()),
                        new Bin("DEST_CITY_NAME", flight[12].trim()),
                        new Bin("DEST_STATE_ABR", flight[13].trim()),
                        new Bin("DEP_TIME", Integer.parseInt(flight[14].trim())),
                        new Bin("ARR_TIME", Integer.parseInt(flight[15].trim())),
                        new Bin("ELAPSED_TIME", Integer.parseInt(flight[16].trim())),
                        new Bin("AIR_TIME", Integer.parseInt(flight[17].trim())),
                        new Bin("DISTANCE", Integer.parseInt(flight[18].trim())));

                log.debug("Flight [ID= " + flight[0] + " , year=" + flight[1] + " , DAY_OF_MONTH=" + flight[2]
                        + " , FL_DATE=" + flight[3] + " , AIRLINE_ID=" + flight[4] + " , CARRIER=" + flight[5]
                        + " , FL_NUM=" + flight[6] + " , ORIGIN_AIRPORT_ID=" + flight[7] + "]");

            }
            br.close();
            log.info("Successfully uploaded " + name);
            return "You successfully uploaded " + name;
        } catch (Exception e) {
            log.error("Failed to upload " + name, e);
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        log.info("Failed to upload " + name + " because the file was empty.");
        return "You failed to upload " + name + " because the file was empty.";
    }
}

From source file:net.longfalcon.web.AdminGameController.java

@RequestMapping(value = "/admin/console-edit", method = RequestMethod.POST)
public View editConsolePost(@ModelAttribute("consoleInfo") ConsoleInfoVO consoleInfoVo, Model model)
        throws NoSuchResourceException, FileUploadException {
    MultipartFile file = consoleInfoVo.getMultipartFile();
    long id;//from   w w w.  j a  v  a 2  s.co  m
    InputStream coverStream = null;
    try {
        if (file != null && !file.isEmpty()) {
            coverStream = file.getInputStream();
        }
        ConsoleInfo consoleInfo = populateConsoleInfo(consoleInfoVo);
        gameService.updateConsoleInfo(consoleInfo, coverStream);
        id = consoleInfo.getId();
    } catch (Exception e) {
        _log.error(e, e);
        throw new FileUploadException();
    }

    return safeRedirect("/admin/console-edit?id=" + id);
}

From source file:onlinevideostore.controller.MovieController.java

@RequestMapping(value = "/addMovie", method = RequestMethod.POST)
public String addMovies(@Valid Movies movies, BindingResult result, Model model, HttpServletRequest request) {
    //javax.swing.JOptionPane.showMessageDialog(null, "hello");
    if (result.hasErrors()) {
        // javax.swing.JOptionPane.showMessageDialog(null, "hello2");

        return "addmovie";
    } else {/*w  w w .j a  v a  2 s.c  o  m*/

        MultipartFile carImage = movies.getImage();
        //String rootDirectory = request.getSession().getServletContext().getRealPath("/");

        if (carImage != null && !carImage.isEmpty()) {
            try {
                carImage.transferTo(new File(saveDirectory + movies.getTitle() + ".png"));
            } catch (Exception e) {
                throw new RuntimeException("Product Image saving failed", e);
            }
        }

        movieService.addMovie(movies);
        // javax.swing.JOptionPane.showMessageDialog(null, movies.getTitle());
        model.addAttribute("movies", movies);
        return "movieDetail";
    }
}

From source file:cn.newgxu.lab.info.controller.NoticeController.java

private void fileUpload(Notice info, String fileName, MultipartFile file) {
    try {/*  w w w. j  a v  a  2s . c o  m*/
        if (!file.isEmpty()) {
            uploadable(file);
            String originName = file.getOriginalFilename();
            Calendar now = Calendar.getInstance();
            String path = now.get(Calendar.YEAR) + "/" + (now.get(Calendar.MONTH) + 1);
            File dir = new File(Config.UPLOAD_ABSOLUTE_DIR + Config.UPLOAD_RELATIVE_DIR + path + "/");
            if (!dir.exists()) {
                if (!dir.mkdirs()) {
                    throw new RuntimeException("????");
                }
            }

            String savedFileName = now.getTimeInMillis() + RegexUtils.getFileExt(originName);
            file.transferTo(new File(dir.getAbsolutePath() + "/" + savedFileName));
            info.setDocUrl(Config.UPLOAD_RELATIVE_DIR + path + "/" + savedFileName);
            info.setDocName(fileName);
        }
    } catch (IllegalStateException e) {
        L.error("?", e);
        throw new RuntimeException("?", e);
    } catch (IOException e) {
        L.error("?", e);
        throw new RuntimeException("?", e);
    }
}

From source file:org.hsweb.web.controller.file.FileController.java

/**
 * ,?.???,{@link FileService#saveFile(InputStream, String)}?
 * ??,??:[{"id":"fileId","name":"fileName","md5":"md5"}]
 *
 * @param files /*w w w .  ja v a 2s . c om*/
 * @return .
 * @throws IOException ?
 */
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@AccessLogger("")
public ResponseMessage upload(@RequestParam("file") MultipartFile[] files) throws IOException {
    if (logger.isInfoEnabled())
        logger.info(String.format("start upload , file number:%s", files.length));
    List<Resources> resourcesList = new LinkedList<>();
    for (int i = 0; i < files.length; i++) {
        MultipartFile file = files[i];
        if (!file.isEmpty()) {
            if (logger.isInfoEnabled())
                logger.info("start write file:{}", file.getOriginalFilename());
            String fileName = file.getOriginalFilename();
            Resources resources = fileService.saveFile(file.getInputStream(), fileName);
            resourcesList.add(resources);
        }
    } //????
    return ResponseMessage.ok(resourcesList).include(Resources.class, "id", "name", "md5");
}

From source file:org.socialhistoryservices.pid.controllers.QRController.java

@RequestMapping(value = "/qr", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam("image") MultipartFile file, HttpServletResponse response)
        throws IOException {

    String url = null;/*from w  ww.ja  va2  s .c  o m*/
    if (!file.isEmpty()) {
        try {
            url = qrService.decode(file.getInputStream());
        } catch (Exception e) {
            // Do not do a thing
        }
    }
    if (url == null) {
        response.setStatus(404);
        return "fnf400";
    } else {
        response.setStatus(301);
        response.setHeader("Location", url);
        response.setHeader("Connection", "close");
        return null;
    }
}