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.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();/*  w  ww .  j a va2  s .c om*/

    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:it.cilea.osd.jdyna.editor.FilePropertyEditor.java

@Override
public void setValue(Object value) {
    if (value instanceof MultipartFile) {
        MultipartFile multipart = (MultipartFile) value;
        if (multipart.getSize() > 0) {
            try {
                EmbeddedFile file = widgetFile.load(multipart.getInputStream(), multipart.getOriginalFilename(),
                        multipart.getContentType(), getExternalAuthority(), getInternalAuthority());
                super.setValue(new ValoreDTO(file));
            } catch (IOException ex) {
                log.warn("Cannot read contents of multipart file", ex);
                throw new IllegalArgumentException(
                        "Cannot read contents of multipart file: " + ex.getMessage());

            }//from   ww w .  java 2 s  .  co m
        } else {
            setValue(null);
        }
    } else {
        super.setValue(value);
    }
}

From source file:org.jasig.portlet.test.mvc.tests.FileUploadController.java

@ActionMapping("fileUploadAction")
public void simpleFileUpload(PortletSession portletSession, @RequestParam("file") MultipartFile f)
        throws IOException {
    final Map<String, ? extends Object> fileInfo = ImmutableMap.of("size", f.getSize(), "originalFilename",
            f.getOriginalFilename(), "name", f.getName(), "contentType", f.getContentType(), "byteCount",
            f.getBytes().length);// w  w  w . j a va 2s . c  om

    portletSession.setAttribute(UPLOADED_FILE_INFO, fileInfo);
}

From source file:org.pdfgal.pdfgalweb.utils.impl.FileUtilsImpl.java

@Override
public List<String> saveFile(final List<MultipartFile> files) {

    final List<String> result = new ArrayList<String>();

    if (CollectionUtils.isNotEmpty(files)) {
        for (final MultipartFile file : files) {

            if (file.getSize() > 0) {

                final String path = this.saveFile(file);

                if (StringUtils.isBlank(path)) {
                    this.delete(result);
                    return null;
                }//from  ww w  . ja  va 2  s. c  o m

                result.add(path);
            }
        }
    }

    return result;
}

From source file:no.dusken.aranea.admin.control.EditImageController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object object,
        BindException errors) throws Exception {
    Image image = (Image) object;

    // set the photographer to null if externalsource is set.
    if (request.getParameter("externalsource") != null && request.getParameter("externalsource").length() > 0) {
        image.setPhotographer(null);/*  w ww  .j a v a2  s .  c o  m*/
    }
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile file = multipartRequest.getFile("file_");
    if (file != null && file.getSize() != 0) {
        image = storeImageService.changeImage(file, image);
    }
    return super.onSubmit(request, response, image, errors);
}

From source file:org.pdfgal.pdfgalweb.validators.MergeValidator.java

/**
 * This method validates a files list, it returns a
 * {@link PDFEncryptionType} indicating if one the files is not a PDF, if it
 * is an encrypted PDF or if each one of the are not encrypted PDFs.
 * /*from   w w w  .ja v a  2s  . c o  m*/
 * @param files
 * @return
 */
private PDFEncryptionType validatePDF(final List<MultipartFile> files) {

    PDFEncryptionType result = PDFEncryptionType.NON_ENCRYPTED;

    for (final MultipartFile file : files) {
        if (file.getSize() > 0) {
            final PDFEncryptionType validation = this.validatorUtils.validatePDF(file);
            if (!PDFEncryptionType.NON_ENCRYPTED.equals(validation)) {
                result = validation;
                break;
            }
        }
    }

    return result;
}

From source file:org.zht.framework.web.controller.AjaxUploadController.java

/**
 * @param request//w w w.j a  v  a  2 s  .  c  om
 * @param files
 * @return
 */
@RequestMapping(value = "ajaxUpload", method = RequestMethod.POST)
@ResponseBody
public Object 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");

    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, "UTF-8");
            //                if (ImagesUtils.isImage(filename)) {
            //                    ajaxUploadResponse.add(filename, size, url, url, deleteURL);
            //                } else {
            //                    ajaxUploadResponse.add(filename, size, url, deleteURL);
            //                }
            continue;
        } catch (IOException 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 null;
}

From source file:org.pdfgal.pdfgalweb.validators.MergeValidator.java

/**
 * This method returns true when every file on the list is empty, or the
 * list is empty.//ww w . j  av  a 2  s . c  o  m
 * 
 * @param files
 * @return
 */
private boolean isEmpty(final List<MultipartFile> files) {

    boolean result = true;

    if (CollectionUtils.isNotEmpty(files)) {
        for (final MultipartFile file : files) {
            if (file.getSize() != 0) {
                result = false;
                break;
            }
        }
    }

    return result;
}

From source file:ru.mystamps.web.service.ImageServiceImpl.java

@Override
@Transactional/*from w  w w  .j  a va2 s .  c om*/
@PreAuthorize("isAuthenticated()")
public Integer save(MultipartFile file) {
    Validate.isTrue(file != null, "File must be non null");
    Validate.isTrue(file.getSize() > 0, "Image size must be greater than zero");

    String contentType = file.getContentType();
    Validate.isTrue(contentType != null, "File type must be non null");

    String extension = extractExtensionFromContentType(contentType);
    Validate.validState("png".equals(extension) || "jpeg".equals(extension),
            "File type must be PNG or JPEG image, but '%s' (%s) were passed", contentType, extension);

    String imageType = extension.toUpperCase(Locale.US);

    Integer id = imageDao.add(imageType);
    if (id == null) {
        throw new ImagePersistenceException("Can't save image");
    }

    ImageInfoDto image = new ImageInfoDto(id, imageType);
    LOG.info("Image was saved to database ({})", image);

    imagePersistenceStrategy.save(file, image);

    return image.getId();
}

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

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

    try {// w  ww.j ava 2  s  .c om
        this.fileService.saveFile(file.getInputStream(), file.getSize(), 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");
    }
}