Example usage for org.springframework.web.multipart MultipartFile getSize

List of usage examples for org.springframework.web.multipart MultipartFile getSize

Introduction

In this page you can find the example usage for org.springframework.web.multipart MultipartFile getSize.

Prototype

long getSize();

Source Link

Document

Return the size of the file in bytes.

Usage

From source file:cn.guoyukun.spring.web.controller.AjaxUploadController.java

/**
 * @param request/*w w w .  ja  v  a  2 s . co  m*/
 * @param files
 * @return
 */
@RequestMapping(value = "ajaxUpload", method = RequestMethod.POST)
@ResponseBody
public AjaxUploadResponse ajaxUpload(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "files[]", required = false) MultipartFile[] files) {

    //The file upload plugin makes use of an Iframe Transport module for browsers like Microsoft Internet Explorer and Opera, which do not yet support XMLHTTPRequest file uploads.
    response.setContentType("text/plain");

    AjaxUploadResponse ajaxUploadResponse = new AjaxUploadResponse();

    if (ArrayUtils.isEmpty(files)) {
        return ajaxUploadResponse;
    }

    for (MultipartFile file : files) {
        String filename = file.getOriginalFilename();
        long size = file.getSize();

        try {
            String url = FileUploadUtils.upload(request, baseDir, file, allowedExtension, maxSize, true);
            String deleteURL = "/ajaxUpload/delete?filename=" + URLEncoder.encode(url, Constants.ENCODING);
            if (ImagesUtils.isImage(filename)) {
                ajaxUploadResponse.add(filename, size, url, url, deleteURL);
            } else {
                ajaxUploadResponse.add(filename, size, url, deleteURL);
            }
            continue;
        } catch (IOException e) {
            LogUtils.logError("file upload error", e);
            ajaxUploadResponse.add(filename, size, MessageUtils.message("upload.server.error"));
            continue;
        } catch (InvalidExtensionException e) {
            ajaxUploadResponse.add(filename, size, MessageUtils.message("upload.not.allow.extension"));
            continue;
        } catch (FileUploadBase.FileSizeLimitExceededException e) {
            ajaxUploadResponse.add(filename, size, MessageUtils.message("upload.exceed.maxSize"));
            continue;
        } catch (FileNameLengthLimitExceededException e) {
            ajaxUploadResponse.add(filename, size, MessageUtils.message("upload.filename.exceed.length"));
            continue;
        }
    }
    return ajaxUploadResponse;
}

From source file:com.epam.ta.reportportal.core.user.impl.EditUserHandler.java

private void validatePhoto(MultipartFile file) throws IOException {
    expect(file.getSize() < MAX_PHOTO_SIZE, equalTo(true)).verify(BINARY_DATA_CANNOT_BE_SAVED,
            "Image size should be less than 1 mb");
    MediaType mediaType = new AutoDetectParser().getDetector().detect(TikaInputStream.get(file.getBytes()),
            new Metadata());
    String subtype = mediaType.getSubtype();
    expect(ImageFormat.fromValue(subtype), notNull()).verify(BINARY_DATA_CANNOT_BE_SAVED,
            "Image format should be " + ImageFormat.getValues());
    BufferedImage read = ImageIO.read(file.getInputStream());
    expect((read.getHeight() <= MAX_PHOTO_HEIGHT) && (read.getWidth() <= MAX_PHOTO_WIDTH), equalTo(true))
            .verify(BINARY_DATA_CANNOT_BE_SAVED, "Image size should be 300x500px or less");
}

From source file:com.luna.common.web.controller.AjaxUploadController.java

/**
 * @param request//from  w  w w.  jav  a  2 s .  c  o m
 * @param files
 * @return
 */
@RequestMapping(value = "ajaxUpload", method = RequestMethod.POST)
@ResponseBody
public AjaxUploadResponse ajaxUpload(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "files[]", required = false) MultipartFile[] files) {

    //The file upload plugin makes use of an Iframe Transport module for browsers like Microsoft Internet Explorer and Opera, which do not yet support XMLHTTPRequest file uploads.
    response.setContentType("text/plain");

    AjaxUploadResponse ajaxUploadResponse = new AjaxUploadResponse();

    if (ArrayUtils.isEmpty(files)) {
        return ajaxUploadResponse;
    }

    for (MultipartFile file : files) {
        String filename = file.getOriginalFilename();
        long size = file.getSize();

        try {
            String url = FileUploadUtils.upload(request, baseDir, file, allowedExtension, maxSize, true);
            String deleteURL = "/ajaxUpload/delete?filename=" + URLEncoder.encode(url, Constants.ENCODING);
            if (ImagesUtils.isImage(filename)) {
                ajaxUploadResponse.add(filename, size, url, url, deleteURL);
            } else {
                ajaxUploadResponse.add(filename, size, url, deleteURL);
            }
            continue;
        } catch (IOException e) {
            log.error("file upload error", e);
            ajaxUploadResponse.add(filename, size, MessageUtils.message("upload.server.error"));
            continue;
        } catch (InvalidExtensionException e) {
            ajaxUploadResponse.add(filename, size, MessageUtils.message("upload.not.allow.extension"));
            continue;
        } catch (FileUploadBase.FileSizeLimitExceededException e) {
            ajaxUploadResponse.add(filename, size, MessageUtils.message("upload.exceed.maxSize"));
            continue;
        } catch (FileNameLengthLimitExceededException e) {
            ajaxUploadResponse.add(filename, size, MessageUtils.message("upload.filename.exceed.length"));
            continue;
        }
    }
    return ajaxUploadResponse;
}

From source file:no.dusken.aranea.admin.control.issue.EditIssueController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object o,
        BindException e) throws Exception {
    Issue issue = (Issue) o;/*w  ww  .j a v a2  s  . c o m*/

    MultipartHttpServletRequest mrequest = (MultipartHttpServletRequest) request;
    MultipartFile file = mrequest.getFile("file");
    if (file != null && !file.isEmpty()) {
        issue.setPdfSize(file.getSize());
        String pdfUrl = pdfDirectory + issue.getRelativePdfFilePath();
        // transfer the pdf
        File destFile = new File(pdfUrl);
        destFile.getParentFile().mkdirs();
        file.transferTo(destFile);

        issue.clearPdfPages();
        issueIndexer.tryToIndexIssue(issue);

        try {
            Image image = imageUtils.makeThumbnail(destFile);
            issue.setImage(image);
        } catch (Exception ex) {
            log.error("Error when creating pdf image");
        }
    }
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile image = multipartRequest.getFile("img");
    if (image != null && image.getSize() != 0) {
        Image i = storeImageService.createImage(image);
        issue.setImage(i);
    }
    return super.onSubmit(request, response, issue, e);
}

From source file:com.fengduo.bee.web.controller.upload.FileUploadController.java

/**
 * //from ww w  . ja  v  a  2  s . c  o  m
 */
@RequestMapping(value = "/upload")
public ModelAndView upload(MultipartFile upload, String type) {
    long size = upload.getSize();
    if (size == 0) {
        return createFileJsonMav(ResultCode.ERROR, "", null);
    }
    if (StringUtils.isEmpty(type)) {
        return createFileJsonMav(ResultCode.ERROR, "?", null);
    }
    PicsInfoEnum picInfoEnum = PicsInfoEnum.getEnum(type);
    if (picInfoEnum == null) {
        return createFileJsonMav(ResultCode.ERROR, "?", null);
    }
    int maxSize = picInfoEnum.getMaxSize();
    if (size > maxSize) {
        return createFileJsonMav(ResultCode.ERROR,
                "?" + maxSize / (1024 * 1024) + "MB", null);
    }
    // ???
    String suffix = getSuffix(upload.getOriginalFilename());
    boolean isLegal = checkSuffixLegal(picInfoEnum.getSuffixs(), suffix);
    if (!isLegal) {
        return createFileJsonMav(ResultCode.ERROR, "???", null);
    }
    long userId = getCurrentUserId();
    String relativeUrl = null;
    relativeUrl = picInfoEnum.getDirPrefix() + "/" + userId + "/";
    final String _filePath = relativeUrl;
    Result result = fileService.createFilePath(upload, new IFileCreate() {

        public String build(String filePath, String suffix) {
            return _filePath + filePath + suffix;
        }
    });
    if (result.isSuccess()) {
        return createFileJsonMav(ResultCode.SUCCESS, "?", result.getData().toString());
    } else {
        String msg = "!";
        if (result.getData() != null) {
            msg = result.getData().toString();
        }
        return createFileJsonMav(ResultCode.ERROR, msg, null);
    }
}

From source file:com.trenako.web.images.validation.ImageValidator.java

@Override
public boolean isValid(MultipartFile file, ConstraintValidatorContext context) {
    // skip validation for empty files.
    if (file == null || file.isEmpty())
        return true;

    // validate file size
    if (file.getSize() > AppGlobals.MAX_UPLOAD_SIZE) {
        return false;
    }/*from   w ww . j a  v a2  s  .com*/

    // validate content type
    MediaType contentType = MediaType.parseMediaType(file.getContentType());
    if (!AppGlobals.ALLOWED_MEDIA_TYPES.contains(contentType.toString())) {
        return false;
    }

    return true;
}

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

private boolean uploadable(MultipartFile file) {
    if (file.getSize() > Config.MAX_FILE_SIZE) {
        throw new IllegalArgumentException("5M??");
    }/*from ww  w  . java  2 s.co m*/

    String fileName = file.getOriginalFilename();
    if (RegexUtils.uploadable(fileName)) {
        return true;
    }
    throw new IllegalArgumentException("???");
}

From source file:com.gothiaforum.validator.actorsform.ImageValidatorTest.java

/**
 * Test whit to large file// w  w w  .  j  a v a  2s .  com
 * 
 * @throws Exception
 *             the exception
 */
@Test
public void test7() throws Exception {

    ImageValidator imageValidator = new ImageValidator();

    List<String> errors = new ArrayList<String>();
    MultipartFile multipartFile = Mockito.mock(MultipartFile.class);

    Mockito.when(multipartFile.getSize()).thenReturn((long) (8 * 1024 * 1024));

    imageValidator.validate(multipartFile, errors);

    assertEquals(1, errors.size());

}

From source file:com.gothiaforum.validator.actorsform.ImageValidatorTest.java

/**
 * Test whit to big file//from   w w  w .  j av  a2  s.  c  o m
 * 
 * @throws Exception
 *             the exception
 */
@Test
public void test8() throws Exception {

    ImageValidator imageValidator = new ImageValidator();

    List<String> errors = new ArrayList<String>();
    MultipartFile multipartFile = Mockito.mock(MultipartFile.class);

    Mockito.when(multipartFile.getSize()).thenReturn((long) (-10));

    imageValidator.validate(multipartFile, errors);

    assertEquals(1, errors.size());

}

From source file:com.gothiaforum.validator.actorsform.ImageValidatorTest.java

/**
 * Test watch should work for jpg file/*from   w  ww.j a  va 2s.c om*/
 * 
 * @throws Exception
 *             the exception
 */
@Test
public void test2() throws Exception {

    ImageValidator imageValidator = new ImageValidator();

    List<String> errors = new ArrayList<String>();
    MultipartFile multipartFile = Mockito.mock(MultipartFile.class);

    Mockito.when(multipartFile.getSize()).thenReturn((long) (1 * 1024 * 1024));
    Mockito.when(multipartFile.getOriginalFilename()).thenReturn("my-image.jpg");
    Mockito.when(multipartFile.getContentType()).thenReturn("image/jpeg");

    imageValidator.validate(multipartFile, errors);

    assertEquals(0, errors.size());

}