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:com.gothiaforum.validator.actorsform.ImageValidatorTest.java

/**
 * Test watch should work for png file./*  w w  w . jav a  2s . c om*/
 * 
 * @throws Exception
 *             the exception
 */
@Test
public void test3() 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.png");
    Mockito.when(multipartFile.getContentType()).thenReturn("image/png");

    imageValidator.validate(multipartFile, errors);

    assertEquals(0, errors.size());

}

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

/**
 * Test watch should work for gif file.//from  w ww  . j  av a2  s  .c o  m
 * 
 * @throws Exception
 *             the exception
 */
@Test
public void test4() 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.gif");
    Mockito.when(multipartFile.getContentType()).thenReturn("image/gif");

    imageValidator.validate(multipartFile, errors);

    assertEquals(0, errors.size());

}

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

/**
 * Test watch should work for x-png file
 * /* w w w  .ja  v a  2 s  . c  om*/
 * @throws Exception
 *             the exception
 */
@Test
public void test5() 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.png");
    Mockito.when(multipartFile.getContentType()).thenReturn("image/x-png");

    imageValidator.validate(multipartFile, errors);

    assertEquals(0, errors.size());

}

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

/**
 * Test with wrong filename and wrong content type.
 * /*from ww w.  j ava 2s. c  o m*/
 * @throws Exception
 *             the exception
 */
@Test
public void test6() 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.pizza");
    Mockito.when(multipartFile.getContentType()).thenReturn("image/pizza");

    imageValidator.validate(multipartFile, errors);

    assertEquals(2, errors.size());

}

From source file:com.glaf.core.web.springmvc.MxDBUploadJsonController.java

@RequestMapping
public void upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
    response.setContentType("text/html; charset=UTF-8");

    LoginContext loginContext = RequestUtils.getLoginContext(request);

    // ???//from   w w  w  . j  av a2 s  .c  om
    String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp", "swf" };
    // ?
    long maxSize = FileUtils.MB_SIZE * 5;

    String allowSize = CustomProperties.getString("upload.maxSize");
    if (StringUtils.isEmpty(allowSize)) {
        allowSize = SystemProperties.getString("upload.maxSize");
    }

    if (StringUtils.isNotEmpty(allowSize) && StringUtils.isNumeric(allowSize)) {
        maxSize = Long.parseLong(allowSize);
    }

    MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
    String businessKey = request.getParameter("businessKey");
    String serviceKey = request.getParameter("serviceKey");
    Map<String, MultipartFile> fileMap = req.getFileMap();
    Set<Entry<String, MultipartFile>> entrySet = fileMap.entrySet();
    for (Entry<String, MultipartFile> entry : entrySet) {
        MultipartFile mFile = entry.getValue();
        if (mFile.getOriginalFilename() != null && mFile.getSize() > 0) {
            // ?
            if (mFile.getSize() > maxSize) {
                response.getWriter().write(getError("??"));
                return;
            }
            String fileName = mFile.getOriginalFilename();
            // ??
            String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            if (!Arrays.<String>asList(fileTypes).contains(fileExt)) {
                response.getWriter().write(getError("??????"));
                return;
            }
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String newFileName = df.format(new Date()) + "_" + new Random().nextInt(10000) + "." + fileExt;
            try {
                DataFile dataFile = new BlobItemEntity();
                dataFile.setBusinessKey(businessKey);
                dataFile.setCreateBy(loginContext.getActorId());
                dataFile.setCreateDate(new Date());
                dataFile.setFileId(newFileName);
                dataFile.setLastModified(System.currentTimeMillis());
                dataFile.setName(fileName);
                if (StringUtils.isNotEmpty(serviceKey)) {
                    dataFile.setServiceKey(serviceKey);
                } else {
                    dataFile.setServiceKey("IMG_" + loginContext.getActorId());
                }
                dataFile.setData(mFile.getBytes());
                dataFile.setFilename(fileName);
                dataFile.setType(fileExt);
                dataFile.setSize(mFile.getSize());
                dataFile.setStatus(1);
                blobService.insertBlob(dataFile);
            } catch (Exception ex) {
                ex.printStackTrace();
                response.getWriter().write(getError(""));
                return;
            }

            JSONObject object = new JSONObject();
            object.put("error", 0);
            object.put("url", request.getContextPath() + "/rs/blob/file/" + newFileName);
            response.getWriter().write(object.toString());
        }
    }
}

From source file:org.jhk.pulsing.web.controller.UserController.java

@RequestMapping(value = "/createUser", method = RequestMethod.POST, consumes = {
        MediaType.MULTIPART_FORM_DATA_VALUE })
public @ResponseBody Result<User> createUser(@RequestParam User user,
        @RequestParam(name = "picture", required = false) MultipartFile mPicture) {
    _LOGGER.debug("UserController.createUser: " + user + "; "
            + (mPicture != null ? ("picture size is: " + mPicture.getSize()) : "picture not submitted"));

    if (mPicture != null) {
        try {/*w w w . j  a v  a  2  s  .  com*/
            ByteBuffer pBuffer = ByteBuffer.wrap(mPicture.getBytes());

            Picture picture = Picture.newBuilder().build();
            picture.setContent(pBuffer);
            picture.setName(mPicture.getOriginalFilename());
            user.setPicture(picture);
        } catch (IOException iException) {
            _LOGGER.error("Could not get picture bytes", iException);
        }
    }

    return userService.createUser(user);
}

From source file:net.przemkovv.sphinx.web.TaskSolutionController.java

private Set<File> acquireFiles(MultipartHttpServletRequest request) throws IOException {
    Set<File> files = new HashSet<>();
    //1. build an iterator
    Iterator<String> itr = request.getFileNames();
    List<MultipartFile> multipartFiles = null;
    //2. get each file
    while (itr.hasNext()) {

        //2.1 get next MultipartFile
        multipartFiles = request.getFiles(itr.next());

        for (MultipartFile multipartFile : multipartFiles) {
            if (multipartFile.getSize() == 0)
                continue;
            ;// ww w.  j  av  a  2 s  . co  m
            logger.debug("{} uploaded! ", multipartFile.getOriginalFilename());

            //2.3 create new fileMeta
            File fileMeta = new File();
            fileMeta.setName(multipartFile.getOriginalFilename());
            fileMeta.setSize(multipartFile.getSize());
            fileMeta.setMimeType(multipartFile.getContentType());

            fileMeta.setContent(multipartFile.getBytes());
            //2.4 add to files

            files.add(fileMeta);
        }

    }
    // result will be like this
    // [{"fileName":"app_engine-85x77.png","fileSize":"8 Kb","fileType":"image/png"},...]
    return files;
}

From source file:eu.freme.broker.eservices.EPublishing.java

@RequestMapping(value = "/e-publishing/html", method = RequestMethod.POST)
public ResponseEntity<byte[]> htmlToEPub(@RequestParam("htmlZip") MultipartFile file,
        @RequestParam("metadata") String jMetadata)
        throws InvalidZipException, EPubCreationException, IOException, MissingMetadataException {

    if (file.getSize() > maxUploadSize) {
        double size = maxUploadSize / (1024.0 * 1024);
        return new ResponseEntity<>(new byte[0], HttpStatus.BAD_REQUEST);
        //throw new BadRequestException(String.format("The uploaded file is too large. The maximum file size for uploads is %.2f MB", size));
    }/*from  ww  w.  j a  v a  2 s .com*/

    Gson gson = new Gson();
    Metadata metadata = gson.fromJson(jMetadata, Metadata.class);
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.add("Content-Type", "application/epub+zip");
    try {
        return new ResponseEntity<>(entityAPI.createEPUB(metadata, file.getInputStream()), HttpStatus.OK);
    } catch (InvalidZipException | EPubCreationException | IOException | MissingMetadataException ex) {
        logger.log(Level.SEVERE, ex.getMessage());
        throw ex;
    }
}

From source file:io.restassured.examples.springmvc.controller.FileUploadController.java

@RequestMapping(value = "/textAndReturnHeader", method = POST, consumes = "multipart/mixed", produces = APPLICATION_JSON_VALUE)
public ResponseEntity<String> fileUploadWithControlNameEqualToSomething(
        @RequestHeader("Content-Type") String requestContentType,
        @RequestParam(value = "something") MultipartFile file) {
    return ResponseEntity.ok().header(APPLICATION_JSON_VALUE).header("X-Request-Header", requestContentType)
            .body("{ \"size\" : " + file.getSize() + ", \"name\" : \"" + file.getName()
                    + "\", \"originalName\" : \"" + file.getOriginalFilename() + "\", \"mimeType\" : \""
                    + file.getContentType() + "\" }");
}

From source file:com.cloudbees.demo.beesshop.web.ProductController.java

/**
 * @param id    id of the product//w  w  w  .ja v  a  2 s  .c o m
 * @param photo to associate with the product
 * @return redirection to display product
 */
@RequestMapping(value = "/product/{id}/photo", method = RequestMethod.POST)
@Transactional
public String updatePhoto(@PathVariable long id, @RequestParam("photo") MultipartFile photo) {

    if (photo.getSize() == 0) {
        logger.info("Empty uploaded file");
    } else {
        try {
            String contentType = fileStorageService.findContentType(photo.getOriginalFilename());
            if (contentType == null) {
                logger.warn("Skip file with unsupported extension '{}'", photo.getName());
            } else {

                InputStream photoInputStream = photo.getInputStream();
                long photoSize = photo.getSize();

                ObjectMetadata objectMetadata = new ObjectMetadata();
                objectMetadata.setContentLength(photoSize);
                objectMetadata.setContentType(contentType);
                objectMetadata
                        .setCacheControl("public, max-age=" + TimeUnit.SECONDS.convert(365, TimeUnit.DAYS));
                String photoUrl = fileStorageService.storeFile(photoInputStream, objectMetadata);

                Product product = productRepository.get(id);
                logger.info("Saved {}", photoUrl);
                product.setPhotoUrl(photoUrl);
                productRepository.update(product);
            }

        } catch (IOException e) {
            throw Throwables.propagate(e);
        }
    }
    return "redirect:/product/" + id;
}