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:julie.com.mikaelson.file.controller.FileInfoController.java

public @ResponseBody String handleFileUpload(@RequestParam("name") String name,
        @RequestParam("file") MultipartFile file) {
    if (!file.isEmpty()) {
        try {//  w w  w  .  ja  v a2s .  co m
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(
                    new FileOutputStream(new File(name + "-uploaded")));
            stream.write(bytes);
            stream.close();
            return "You successfully uploaded " + name + " into " + name + "-uploaded !";
        } 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.openxdata.server.servlet.FormOpenServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from  w w  w  .jav  a 2 s  .  c o  m
        CommonsMultipartResolver multipartResover = new CommonsMultipartResolver(/*this.getServletContext()*/);
        if (multipartResover.isMultipart(request)) {
            MultipartHttpServletRequest multipartRequest = multipartResover.resolveMultipart(request);
            MultipartFile uploadedFile = multipartRequest.getFile("filecontents");
            if (uploadedFile != null && !uploadedFile.isEmpty())
                request.getSession().setAttribute(KEY_FILE_CONTENTS,
                        IOUtils.toString(uploadedFile.getInputStream(), "UTF-8"));
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.greglturnquist.springagram.fileservice.mongodb.ApplicationController.java

@RequestMapping(method = RequestMethod.POST, value = "/files")
public ResponseEntity<?> newFile(@RequestParam("name") String filename,
        @RequestParam("file") MultipartFile file) {

    if (!file.isEmpty()) {
        try {// w ww  .j  a v  a2s. c o  m
            this.fileService.saveFile(file.getInputStream(), filename);

            Link link = linkTo(methodOn(ApplicationController.class).getFile(filename)).withRel(filename);
            return ResponseEntity.created(new URI(link.getHref())).build();

        } catch (IOException | URISyntaxException e) {
            return ResponseEntity.badRequest().body("Couldn't process the request");
        }
    } else {
        return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body("File is empty");
    }
}

From source file:com.facerecog.rest.controller.RecognitionController.java

@RequestMapping(value = ApiUrls.URL_RECOG_UPLOAD_IMAGE, method = RequestMethod.POST)
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
    logger.info("File upload");

    if (!file.isEmpty()) {
        try {//ww w .  ja va  2s .  c  o  m
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(
                    new FileOutputStream(new File(file.getOriginalFilename())));
            stream.write(bytes);
            stream.close();
            return "File uploaded: " + file.getOriginalFilename();
        } catch (Exception e) {
            return "Failed to upload image!";
        }
    } else {
        return "Failed to upload file because the file was empty.";
    }
}

From source file:org.opensprout.osaf.propertyeditor.FilePropertyEditor.java

/** MultipartFile -> File(uploadFolder/filename) */
public void setValue(Object value) {
    if (value instanceof MultipartFile) {
        MultipartFile multipartFile = (MultipartFile) value;

        // if there is no file
        if (multipartFile.isEmpty()) {
            this.logger.debug("Filename: null");
            super.setValue(null);
            return;
        }/*from   w  w w.  j  av a2  s  .  c  o  m*/

        String fileName = makeDuplicationSafeFileName(multipartFile.getOriginalFilename());
        this.logger.debug("Filename : " + fileName);
        String path = uploadDirectory + "/" + fileName;

        // transfer file
        try {
            multipartFile.transferTo(new File(path));
        } catch (IOException e) {
            this.logger.debug("Multipart Error : " + e.getMessage());
            throw new OSAFException("Check upload folder  : [" + uploadDirectory + "]."
                    + "Nested exception is : " + e.getMessage());
        }
        super.setValue(path);
    } else {
        super.setValue(null);
    }
}

From source file:org.opensafety.hishare.controller.UploadParcelController.java

@RequestMapping(value = "/file", method = RequestMethod.POST)
public ModelAndView handleFormUpload(@RequestParam("username") String username,
        @RequestParam("authenticationId") String authenticationId,
        @RequestParam("parcelName") String parcelName, @RequestParam("daysToLive") Integer daysToLive,
        @RequestParam("file") MultipartFile file) throws IOException {
    ModelAndView mav;//from w  ww  .  j a v  a  2  s  . c  o  m

    byte[] payload = null;

    if (!file.isEmpty()) {
        payload = file.getBytes();
    }

    mav = new ModelAndView("outputString");
    String[] accessInfo = uploadParcel.uploadParcel(username, authenticationId, parcelName, daysToLive,
            payload);
    String output = accessInfo[0] + ":" + accessInfo[1];
    mav.addObject("string", output);

    return mav;
}

From source file:net.shopxx.controller.admin.FileController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody Map<String, Object> upload(FileType fileType, MultipartFile file) {
    Map<String, Object> data = new HashMap<String, Object>();
    if (fileType == null || file == null || file.isEmpty()) {
        data.put("message", ERROR_MESSAGE);
        data.put("state", message("admin.message.error"));
        return data;
    }/*w w w  .j  a  v a2s . c  o  m*/
    if (!fileService.isValid(fileType, file)) {
        data.put("message", Message.warn("admin.upload.invalid"));
        data.put("state", message("admin.upload.invalid"));
        return data;
    }
    String url = fileService.upload(fileType, file, false);
    if (StringUtils.isEmpty(url)) {
        data.put("message", Message.warn("admin.upload.error"));
        data.put("state", message("admin.upload.error"));
        return data;
    }
    data.put("message", SUCCESS_MESSAGE);
    data.put("state", "SUCCESS");
    data.put("url", url);
    return data;
}

From source file:io.github.microcks.web.ImportController.java

@RequestMapping(value = "/import", method = RequestMethod.POST)
public ResponseEntity<?> importRepository(@RequestParam(value = "file") MultipartFile file) {
    log.debug("Importing new services and resources definitions");
    if (!file.isEmpty()) {
        log.debug("Content type of " + file.getOriginalFilename() + " is " + file.getContentType());
        if (MediaType.APPLICATION_JSON_VALUE.equals(file.getContentType())) {
            try {
                byte[] bytes = file.getBytes();
                String json = new String(bytes);
                importExportService.importRepository(json);
            } catch (Exception e) {
                log.error(e.getMessage());
            }//from w w  w .  j  av  a 2 s .co  m
        }
    }
    return new ResponseEntity<Object>(HttpStatus.CREATED);
}

From source file:com.capstone.giveout.controllers.UsersController.java

private void saveImages(User user, MultipartFile image) throws IOException {
    if (image == null || image.isEmpty())
        return;//w ww  .  j  ava 2s.  c o  m

    BufferedImage img = ImageIO.read(image.getInputStream());
    ImageFileManager imgMan = ImageFileManager.get(USERS_ROOT_PATH);

    imgMan.saveImage(user.getId(), User.SIZE_FULL, img);
    user.setImageUrlFull(Routes.USERS_IMAGE_PATH.replace("{id}", String.valueOf(user.getId())).replace("{size}",
            User.SIZE_FULL));

    BufferedImage scaledImg = Scalr.resize(img, 640);
    imgMan.saveImage(user.getId(), User.SIZE_MEDIUM, scaledImg);
    user.setImageUrlMedium(Routes.USERS_IMAGE_PATH.replace("{id}", String.valueOf(user.getId()))
            .replace("{size}", User.SIZE_MEDIUM));

    users.save(user);
}

From source file:app.service.ResourceService.java

public int upload(MultipartFile file, int resourceType, StringResource resource) {
    if (file.isEmpty()) {
        return ResultCode.FILE_EMPTY;
    }//w w w.j  av a2s . co  m

    String path;
    if (resourceType == RESOURCE_TYPE_AVATAR) {
        path = RESOURCE_AVATAR_PATH;
    } else if (resourceType == RESOURCE_TYPE_COMMON) {
        path = RESOURCE_COMMON_PATH;
    } else {
        return ResultCode.UNKNOWN_RESOURCE;
    }

    resolvePath(path);
    String filename = resolveFilename(file.getOriginalFilename());
    try {
        OutputStream out = new FileOutputStream(new File(path + "/" + filename));
        BufferedOutputStream stream = new BufferedOutputStream(out);
        FileCopyUtils.copy(file.getInputStream(), stream);
        stream.close();
        resource.filename = filename;
    } catch (Exception e) {
        logger.warn("upload file failure", e);
        return ResultCode.UPLOAD_FILE_FAILED;
    }
    return BaseResponse.COMMON_SUCCESS;
}