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:mx.edu.um.mateo.activos.web.ActivoController.java

@RequestMapping("/subeImagen")
public String subeImagen(@RequestParam Long activoId,
        @RequestParam(value = "imagen", required = false) MultipartFile archivo,
        RedirectAttributes redirectAttributes) {
    log.debug("Subiendo imagen para activo {}", activoId);
    try {/*from   w w  w  . j  a  v a  2 s  .  c o  m*/
        if (archivo != null && !archivo.isEmpty()) {
            Usuario usuario = ambiente.obtieneUsuario();
            Activo activo = activoDao.obtiene(activoId);
            Imagen imagen = new Imagen(archivo.getOriginalFilename(), archivo.getContentType(),
                    archivo.getSize(), archivo.getBytes());
            activo.getImagenes().add(imagen);
            activoDao.subeImagen(activo, usuario);
        }
        redirectAttributes.addFlashAttribute("message", "activo.sube.imagen.message");
        redirectAttributes.addFlashAttribute("messageStyle", "alert-success");
    } catch (IOException e) {
        log.error("Hubo un problema al intentar subir la imagen del activo", e);
    }
    return "redirect:/activoFijo/activo/ver/" + activoId;
}

From source file:architecture.ee.web.spring.controller.MyCloudDataController.java

@PreAuthorize("hasAuthority('ROLE_USER')")
@RequestMapping(value = "/files/upload.json", method = RequestMethod.POST)
@ResponseBody/*from   w ww .j  a  va2  s. c  om*/
public List<Attachment> uploadFiles(
        @RequestParam(value = "objectType", defaultValue = "2", required = false) Integer objectType,
        @RequestParam(value = "fileId", defaultValue = "0", required = false) Long fileId,
        MultipartHttpServletRequest request) throws NotFoundException, IOException {
    User user = SecurityHelper.getUser();
    Iterator<String> names = request.getFileNames();
    List<Attachment> list = new ArrayList<Attachment>();
    while (names.hasNext()) {
        String fileName = names.next();
        log.debug(fileName);
        MultipartFile mpf = request.getFile(fileName);
        InputStream is = mpf.getInputStream();
        log.debug("fileId: " + fileId);
        log.debug("file name: " + mpf.getOriginalFilename());
        log.debug("file size: " + mpf.getSize());
        log.debug("file type: " + mpf.getContentType());
        log.debug("file class: " + is.getClass().getName());

        Attachment attachment;
        if (fileId > 0) {
            attachment = attachmentManager.getAttachment(fileId);
            attachment.setName(mpf.getOriginalFilename());
            ((AttachmentImpl) attachment).setInputStream(is);
            ((AttachmentImpl) attachment).setSize((int) mpf.getSize());
        } else {
            attachment = attachmentManager.createAttachment(objectType, user.getUserId(),
                    mpf.getOriginalFilename(), mpf.getContentType(), is, (int) mpf.getSize());
        }

        attachmentManager.saveAttachment(attachment);
        list.add(attachment);
    }
    return list;
}

From source file:fr.univrouen.poste.web.membre.PosteAPourvoirController.java

@RequestMapping(value = "/{id}/addFile", method = RequestMethod.POST, produces = "text/html")
@PreAuthorize("hasPermission(#id, 'manageposte')")
public String addFile(@PathVariable("id") Long id, @Valid PosteAPourvoirFile posteFile,
        BindingResult bindingResult, Model uiModel, HttpServletRequest request) throws IOException {
    if (bindingResult.hasErrors()) {
        logger.warn(bindingResult.getAllErrors());
        return "redirect:/posteapourvoirs/" + id.toString();
    }/*  w w  w .jav  a 2 s  .  c  o m*/
    uiModel.asMap().clear();

    PosteAPourvoir poste = PosteAPourvoir.findPosteAPourvoir(id);

    // upload file
    MultipartFile file = posteFile.getFile();

    // sometimes file is null here, but I don't know how to reproduce this issue ... maybe that can occur only with some specifics browsers ?
    if (file != null) {
        String filename = file.getOriginalFilename();

        boolean filenameAlreadyUsed = false;
        for (PosteAPourvoirFile pcFile : poste.getPosteFiles()) {
            if (pcFile.getFilename().equals(filename)) {
                filenameAlreadyUsed = true;
                break;
            }
        }

        if (filenameAlreadyUsed) {
            uiModel.addAttribute("filename_already_used", filename);
            logger.warn("Upload Restriction sur '" + filename
                    + "' un fichier de mme nom existe dj pour le poste " + poste.getNumEmploi());
        } else {

            Long fileSize = file.getSize();

            if (fileSize != 0) {
                String contentType = file.getContentType();
                // cf https://github.com/EsupPortail/esup-dematec/issues/8 - workaround pour viter mimetype erron comme application/text-plain:formatted
                contentType = contentType.replaceAll(":.*", "");

                logger.info("Try to upload file '" + filename + "' with size=" + fileSize + " and contentType="
                        + contentType);

                InputStream inputStream = file.getInputStream();
                //byte[] bytes = IOUtils.toByteArray(inputStream);

                posteFile.setFilename(filename);
                posteFile.setFileSize(fileSize);
                posteFile.setContentType(contentType);
                logger.info("Upload and set file in DB with filesize = " + fileSize);
                posteFile.getBigFile().setBinaryFileStream(inputStream, fileSize);
                posteFile.getBigFile().persist();

                Calendar cal = Calendar.getInstance();
                Date currentTime = cal.getTime();
                posteFile.setSendTime(currentTime);

                poste.getPosteFiles().add(posteFile);
                poste.persist();

                logService.logActionPosteFile(LogService.UPLOAD_ACTION, poste, posteFile, request, currentTime);
            }
        }
    } else {
        String userId = SecurityContextHolder.getContext().getAuthentication().getName();
        String ip = request.getRemoteAddr();
        String userAgent = request.getHeader("User-Agent");
        logger.warn(userId + "[" + ip + "] tried to add a 'null file' ... his userAgent is : " + userAgent);
    }

    return "redirect:/posteapourvoirs/" + id.toString();
}

From source file:architecture.ee.web.spring.controller.MyCloudDataController.java

@Secured({ "ROLE_USER" })
@RequestMapping(value = "/me/photo/images/update_with_media.json", method = RequestMethod.POST)
@ResponseBody/*from   ww  w.  j a v a  2s  .  c  o m*/
public List<Image> uploadMyImageWithMedia(
        @RequestParam(value = "imageId", defaultValue = "0", required = false) Long imageId,
        MultipartHttpServletRequest request) throws NotFoundException, IOException {
    User user = SecurityHelper.getUser();

    if (user.isAnonymous())
        throw new UnAuthorizedException();

    Iterator<String> names = request.getFileNames();
    List<Image> list = new ArrayList<Image>();
    while (names.hasNext()) {
        String fileName = names.next();
        log.debug(fileName);
        MultipartFile mpf = request.getFile(fileName);
        InputStream is = mpf.getInputStream();
        log.debug("imageId: " + imageId);
        log.debug("file name: " + mpf.getOriginalFilename());
        log.debug("file size: " + mpf.getSize());
        log.debug("file type: " + mpf.getContentType());
        log.debug("file class: " + is.getClass().getName());
        Image image;
        if (imageId > 0) {
            image = imageManager.getImage(imageId);

            image.setName(mpf.getOriginalFilename());
            ((ImageImpl) image).setInputStream(is);
            ((ImageImpl) image).setSize((int) mpf.getSize());
        } else {
            image = imageManager.createImage(2, user.getUserId(), mpf.getOriginalFilename(),
                    mpf.getContentType(), is, (int) mpf.getSize());
            image.setUser(user);
        }
        log.debug(hasPermissions(image, user));
        imageManager.saveImage(image);
        list.add(image);
    }
    return list;
}

From source file:architecture.ee.web.spring.controller.MyCloudDataController.java

@PreAuthorize("hasAuthority('ROLE_USER')")
@RequestMapping(value = "/images/update_with_media.json", method = RequestMethod.POST)
@ResponseBody//www  .  j a v  a  2 s  . co m
public List<Image> uploadImageWithMedia(
        @RequestParam(value = "objectType", defaultValue = "2", required = false) Integer objectType,
        @RequestParam(value = "objectId", defaultValue = "0", required = false) Long objectId,
        @RequestParam(value = "imageId", defaultValue = "0", required = false) Long imageId,
        MultipartHttpServletRequest request) throws NotFoundException, IOException {
    User user = SecurityHelper.getUser();
    if (objectType == 1) {
        objectId = user.getCompanyId();
    } else if (objectType == 2) {
        objectId = user.getUserId();
    } else if (objectType == 30) {
        objectId = WebSiteUtils.getWebSite(request).getWebSiteId();
    }

    Iterator<String> names = request.getFileNames();
    List<Image> list = new ArrayList<Image>();
    while (names.hasNext()) {
        String fileName = names.next();
        log.debug(fileName);
        MultipartFile mpf = request.getFile(fileName);
        InputStream is = mpf.getInputStream();
        log.debug("imageId: " + imageId);
        log.debug("file name: " + mpf.getOriginalFilename());
        log.debug("file size: " + mpf.getSize());
        log.debug("file type: " + mpf.getContentType());
        log.debug("file class: " + is.getClass().getName());

        Image image;
        if (imageId > 0) {
            image = imageManager.getImage(imageId);
            image.setName(mpf.getOriginalFilename());
            ((ImageImpl) image).setInputStream(is);
            ((ImageImpl) image).setSize((int) mpf.getSize());
        } else {
            image = imageManager.createImage(objectType, objectId, mpf.getOriginalFilename(),
                    mpf.getContentType(), is, (int) mpf.getSize());
            image.setUser(user);
        }
        log.debug(hasPermissions(image, user));
        imageManager.saveImage(image);
        list.add(image);
    }
    return list;
}

From source file:net.duckling.ddl.web.api.rest.FileEditController.java

@RequestMapping(value = "/files", method = RequestMethod.POST)
public void upload(@RequestParam(value = "path", required = false) String path,
        @RequestParam("file") MultipartFile file,
        @RequestParam(value = "ifExisted", required = false) String ifExisted, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    String uid = getCurrentUid(request);
    int tid = getCurrentTid();
    path = StringUtils.defaultIfBlank(path, PathName.DELIMITER);

    Resource parent = folderPathService.getResourceByPath(tid, path);
    if (parent == null) {
        writeError(ErrorMsg.NOT_FOUND, response);
        return;// w w w  .  j  a  v a2 s .  c  o  m
    }

    List<Resource> list = resourceService.getResourceByTitle(tid, parent.getRid(), LynxConstants.TYPE_FILE,
            file.getOriginalFilename());
    if (list.size() > 0 && !IF_EXISTED_UPDATE.equals(ifExisted)) {
        writeError(ErrorMsg.EXISTED, response);
        return;
    }

    FileVersion fv = null;
    try {
        fv = resourceOperateService.upload(uid, super.getCurrentTid(), parent.getRid(),
                file.getOriginalFilename(), file.getSize(), file.getInputStream());
    } catch (NoEnoughSpaceException e) {
        writeError(ErrorMsg.NO_ENOUGH_SPACE, response);
        return;
    }

    Resource resource = resourceService.getResource(fv.getRid());
    resource.setPath(folderPathService.getPathString(resource.getRid()));
    JsonUtil.write(response, VoUtil.getResourceVo(resource));
}

From source file:org.sakaiproject.imagegallery.integration.standalone.FileLibraryStandalone.java

/**
 * @see org.sakaiproject.imagegallery.integration.FileLibraryService#storeImageFile(org.springframework.web.multipart.MultipartFile)
 *//*w ww  .  j  av  a2s.c  om*/
@Transactional
public ImageFile storeImageFile(final MultipartFile sourceImageFile) {
    final String filename = sourceImageFile.getOriginalFilename();
    final String fileId = contextService.getCurrentContextUid() + "/" + filename;
    final String contentType = sourceImageFile.getContentType();

    ImageFile imageFile = new ImageFile();
    imageFile.setContentType(contentType);
    imageFile.setFilename(filename);
    imageFile.setFileId(fileId);
    imageFile.setDataUrl(urlPrefix + fileId);

    jdbcTemplate.getJdbcOperations().execute(
            "insert into IMAGE_GALLERY_STANDALONE_FILES_T (FILE_ID, CONTENT_TYPE, CONTENT) VALUES (?, ?, ?)",
            new AbstractLobCreatingPreparedStatementCallback(this.lobHandler) {
                protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException {
                    ps.setString(1, fileId);
                    ps.setString(2, contentType);
                    try {
                        lobCreator.setBlobAsBinaryStream(ps, 3, sourceImageFile.getInputStream(),
                                (int) sourceImageFile.getSize());
                    } catch (IOException e) {
                        log.error("Error copying binary data from file " + filename, e);
                    }
                }
            });

    return imageFile;
}

From source file:com.devnexus.ting.web.controller.admin.SponsorController.java

@RequestMapping(value = "/s/admin/{eventKey}/sponsor/{sponsorId}", method = RequestMethod.POST)
public String editSponsor(@PathVariable("sponsorId") Long sponsorId, @RequestParam MultipartFile pictureFile,
        @Valid Sponsor sponsorForm, BindingResult result, RedirectAttributes redirectAttributes,
        HttpServletRequest request) {/*from w w w .j  a  va  2s  .  co  m*/

    if (request.getParameter("cancel") != null) {
        return "redirect:/s/admin/{eventKey}/sponsors";
    }

    if (result.hasErrors()) {
        return "/admin/add-sponsor";
    }

    final Sponsor sponsorFromDb = businessService.getSponsorWithPicture(sponsorId);

    if (request.getParameter("delete") != null) {
        businessService.deleteSponsor(sponsorFromDb);
        redirectAttributes.addFlashAttribute("successMessage", "The sponsor was deleted successfully.");
        return "redirect:/s/admin/{eventKey}/sponsors";
    }

    sponsorFromDb.setLink(sponsorForm.getLink());
    sponsorFromDb.setName(sponsorForm.getName());
    sponsorFromDb.setSortOrder(sponsorForm.getSortOrder());
    sponsorFromDb.setSponsorLevel(sponsorForm.getSponsorLevel());

    if (pictureFile != null && pictureFile.getSize() > 0) {

        final FileData pictureData;
        if (sponsorFromDb.getLogo() == null) {
            pictureData = new FileData();
        } else {
            pictureData = sponsorFromDb.getLogo();
        }

        try {

            pictureData.setFileData(IOUtils.toByteArray(pictureFile.getInputStream()));
            pictureData.setFileSize(pictureFile.getSize());
            pictureData.setFileModified(new Date());
            pictureData.setType(pictureFile.getContentType());
            pictureData.setName(pictureFile.getOriginalFilename());

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        sponsorFromDb.setLogo(pictureData);
    }

    businessService.saveSponsor(sponsorFromDb);

    redirectAttributes.addFlashAttribute("successMessage",
            String.format("The sponsor '%s' was edited successfully.", sponsorFromDb.getName()));

    return "redirect:/s/admin/{eventKey}/sponsors";
}

From source file:architecture.ee.web.spring.controller.SecureWebMgmtDataController.java

@RequestMapping(value = "/mgmt/logo/upload.json", method = RequestMethod.POST)
@ResponseBody/*from w w w  . j  a v a2 s.c o m*/
public Result uploadLogoImage(
        @RequestParam(value = "objectType", defaultValue = "1", required = false) Integer objectType,
        @RequestParam(value = "objectId", defaultValue = "0", required = false) Long objectId,
        MultipartHttpServletRequest request) throws NotFoundException, IOException {

    User user = SecurityHelper.getUser();
    if (objectId == 0) {
        if (objectType == 1) {
            objectId = user.getCompanyId();
        } else if (objectType == 30) {
            objectId = WebSiteUtils.getWebSite(request).getWebSiteId();
        }
    }
    Iterator<String> names = request.getFileNames();
    while (names.hasNext()) {
        String fileName = names.next();
        log.debug(fileName);
        MultipartFile mpf = request.getFile(fileName);
        InputStream is = mpf.getInputStream();
        log.debug("file name: " + mpf.getOriginalFilename());
        log.debug("file size: " + mpf.getSize());
        log.debug("file type: " + mpf.getContentType());
        log.debug("file class: " + is.getClass().getName());

        LogoImage logo = logoManager.createLogoImage();
        logo.setFilename(mpf.getName());
        logo.setImageContentType(mpf.getContentType());
        logo.setImageSize((int) mpf.getSize());
        logo.setObjectType(objectType);
        logo.setObjectId(objectId);
        logo.setPrimary(true);

        logoManager.addLogoImage(logo, mpf.getInputStream());
    }
    return Result.newResult();
}

From source file:gr.abiss.calipso.controller.AbstractServiceBasedRestController.java

@RequestMapping(value = "{subjectId}/uploads/{propertyName}", method = { RequestMethod.POST,
        RequestMethod.PUT }, consumes = {}, produces = { "application/json", "application/xml" })
public @ResponseBody BinaryFile addUploadsToProperty(@PathVariable ID subjectId,
        @PathVariable String propertyName, MultipartHttpServletRequest request, HttpServletResponse response) {
    LOGGER.info("uploadPost called");

    Configuration config = ConfigurationFactory.getConfiguration();
    String fileUploadDirectory = config.getString(ConfigurationFactory.FILES_DIR);
    String baseUrl = config.getString("calipso.baseurl");

    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf;
    BinaryFile bf = new BinaryFile();
    try {//from   ww  w  . j  a v  a  2 s .  c  o m
        if (itr.hasNext()) {

            mpf = request.getFile(itr.next());
            LOGGER.info("Uploading {}", mpf.getOriginalFilename());

            bf.setName(mpf.getOriginalFilename());
            bf.setFileNameExtention(
                    mpf.getOriginalFilename().substring(mpf.getOriginalFilename().lastIndexOf(".") + 1));

            bf.setContentType(mpf.getContentType());
            bf.setSize(mpf.getSize());

            // request targets specific path?
            StringBuffer uploadsPath = new StringBuffer('/')
                    .append(this.service.getDomainClass().getDeclaredField("PATH_FRAGMENT").get(String.class))
                    .append('/').append(subjectId).append("/uploads/").append(propertyName);
            bf.setParentPath(uploadsPath.toString());
            LOGGER.info("Saving image entity with path: " + bf.getParentPath());
            bf = binaryFileService.create(bf);

            LOGGER.info("file name: {}", bf.getNewFilename());
            bf = binaryFileService.findById(bf.getId());
            LOGGER.info("file name: {}", bf.getNewFilename());

            File storageDirectory = new File(fileUploadDirectory + bf.getParentPath());

            if (!storageDirectory.exists()) {
                storageDirectory.mkdirs();
            }

            LOGGER.info("storageDirectory: {}", storageDirectory.getAbsolutePath());
            LOGGER.info("file name: {}", bf.getNewFilename());

            File newFile = new File(storageDirectory, bf.getNewFilename());
            newFile.createNewFile();
            LOGGER.info("newFile path: {}", newFile.getAbsolutePath());
            Files.copy(mpf.getInputStream(), newFile.toPath(), StandardCopyOption.REPLACE_EXISTING);

            BufferedImage thumbnail = Scalr.resize(ImageIO.read(newFile), 290);
            File thumbnailFile = new File(storageDirectory, bf.getThumbnailFilename());
            ImageIO.write(thumbnail, "png", thumbnailFile);
            bf.setThumbnailSize(thumbnailFile.length());

            bf = binaryFileService.update(bf);

            // attach file
            // TODO: add/update to collection
            Field fileField = GenericSpecifications.getField(this.service.getDomainClass(), propertyName);
            Class clazz = fileField.getType();
            if (BinaryFile.class.isAssignableFrom(clazz)) {
                T target = this.service.findById(subjectId);
                BeanUtils.setProperty(target, propertyName, bf);
                this.service.update(target);
            }

            bf.setUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/files/" + bf.getId());
            bf.setThumbnailUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/thumbs/" + bf.getId());
            bf.setDeleteUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/" + bf.getId());
            bf.setDeleteType("DELETE");
            bf.addInitialPreview("<img src=\"" + bf.getThumbnailUrl() + "\" class=\"file-preview-image\" />");

        }

    } catch (Exception e) {
        LOGGER.error("Could not upload file(s) ", e);
    }

    //        Map<String, Object> files= new HashMap<String, Object>();
    //files.put("files", list);
    return bf;
}