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.devnexus.ting.web.controller.admin.AdminScheduleController.java

private List<ScheduleItem> processScheduleCsv(Event event, MultipartFile scheduleCsv,
        BindingResult bindingResult) {//ww  w . j  av a2  s.co  m
    List<ScheduleItem> scheduleItems = new ArrayList<>();
    byte[] scheduleCsvData = null;

    try {
        scheduleCsvData = scheduleCsv.getBytes();
    } catch (IOException e) {
        LOGGER.error("Error processing Schedule CSV File.", e);
        bindingResult.addError(
                new FieldError("uploadScheduleForm", "scheduleFile", "Error processing Schedule CSV File."));
        return null;
    }

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

        final ByteArrayInputStream bais = new ByteArrayInputStream(scheduleCsvData);

        ICsvBeanReader beanReader = null;
        try {
            final Reader reader = new InputStreamReader(bais);
            beanReader = new CsvBeanReader(reader, CsvPreference.STANDARD_PREFERENCE);

            // the header elements are used to map the values to the bean (names must match)
            final String[] header = beanReader.getHeader(true);
            final CellProcessor[] processors = CsvScheduleItemBean.getImportProcessors();

            CsvScheduleItemBean scheduleItemBean;
            while ((scheduleItemBean = beanReader.read(CsvScheduleItemBean.class, header,
                    processors)) != null) {
                final ScheduleItem scheduleItem;

                if (scheduleItemBean.getId() != null) {
                    scheduleItem = businessService.getScheduleItem(scheduleItemBean.getId());
                    if (scheduleItem == null) {
                        LOGGER.error(String.format("Schedule Item with Id '%s' does not exist.",
                                scheduleItemBean.getId()));
                        bindingResult.addError(new FieldError("uploadScheduleForm", "scheduleFile",
                                String.format("Schedule Item with Id '%s' does not exist.",
                                        scheduleItemBean.getId())));
                        continue;
                    }
                } else {
                    scheduleItem = new ScheduleItem();
                }

                if (scheduleItemBean.getEventId() != null) {
                    if (event.getId().equals(scheduleItemBean.getEventId())) {
                        scheduleItem.setEvent(event);
                    } else {
                        throw new IllegalArgumentException("Event ID did not match.");
                    }
                } else {
                    scheduleItem.setEvent(event);
                }

                scheduleItem.setFromTime(scheduleItemBean.getFromTime());
                scheduleItem.setToTime(scheduleItemBean.getToTime());
                scheduleItem.setScheduleItemType(scheduleItemBean.getType());
                scheduleItem.setTitle(scheduleItemBean.getTitle());

                if (scheduleItemBean.getPresentationId() != null) {
                    final Presentation presentation = businessService
                            .getPresentation(scheduleItemBean.getPresentationId());
                    scheduleItem.setPresentation(presentation);
                } else {
                    scheduleItem.setPresentation(null);
                }

                if (scheduleItemBean.getRoomId() != null) {
                    final Room room = businessService.getRoom(scheduleItemBean.getRoomId());
                    scheduleItem.setRoom(room);
                } else {
                    scheduleItem.setRoom(null);
                }

                scheduleItems.add(scheduleItem);

            }
        } catch (IOException e) {
            LOGGER.error("Error processing CSV File.", e);
            bindingResult.addError(new FieldError("uploadScheduleForm", "scheduleFile",
                    "Error processing Schedule CSV File."));
            return null;
        } finally {
            if (beanReader != null) {
                try {
                    beanReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    return scheduleItems;
}

From source file:com.mbv.web.rest.controller.VpGrnController.java

/**
 * @??excel//from ww  w.  ja  v a 2 s.  c  o  m
 * @2015916
 * @param
 * @version
 */
@RequestMapping(value = "/importGrn", method = RequestMethod.POST)
@ResponseBody
public void importBill(@RequestParam(value = "add_vpGrn_importedFile", required = false) MultipartFile file,
        HttpServletRequest request, HttpServletResponse response) {
    JSONObject json = new JSONObject();
    try {
        // ?
        if (file.isEmpty()) {
            throw new MbvException("??");
        }
        // ??
        if (file.getSize() > 20971520) {
            throw new Exception("?20M?");
        }
        json = importFile(file);
    } catch (MbvException me) {
        me.printStackTrace();
        json.put("success", false);
        json.put("msg", me.getMessage());
    } catch (RuntimeException re) {
        re.printStackTrace();
        json.put("success", false);
        json.put("msg", re.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
        json.put("success", false);
        json.put("msg", e.getMessage());
    }
    // ???
    outPrintJson(response, json.toString());
}

From source file:com.mbv.web.rest.controller.VpGrnController.java

/**
 * @??excel//  ww w  .  ja  v  a 2s. com
 * @2015916
 * @param
 * @version
 */
@RequestMapping(value = "/importUpdateGrn", method = RequestMethod.POST)
@ResponseBody
public void importUpdateBill(
        @RequestParam(value = "update_vpGrn_importedFile", required = false) MultipartFile file,
        HttpServletRequest request, HttpServletResponse response) {
    JSONObject json = new JSONObject();
    try {
        // ?
        if (file.isEmpty()) {
            throw new MbvException("??");
        }
        // ??
        if (file.getSize() > 20971520) {
            throw new Exception("?20M?");
        }
        json = importFile(file);
    } catch (MbvException me) {
        me.printStackTrace();
        json.put("success", false);
        json.put("msg", me.getMessage());
    } catch (RuntimeException re) {
        re.printStackTrace();
        json.put("success", false);
        json.put("msg", re.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
        json.put("success", false);
        json.put("msg", e.getMessage());
    }
    // ???
    outPrintJson(response, json.toString());
}

From source file:com.aboutdata.web.controller.member.UploadControler.java

/**
 * ?// w w w. j  a  va2  s .com
 *
 * @param multipartFile
 * @param model
 * @return
 */
@RequestMapping(method = RequestMethod.POST)
public String upload(MultipartFile multipartFile, ModelMap model) {

    Member member = memberService.getCurrent();
    PhotosRequest request = new PhotosRequest();

    //getContentType()  = jpeg/image  png/image
    String type = multipartFile.getContentType().split("/")[1];

    String path = "/tmp/" + multipartFile.getName() + "_" + RandomStringUtils.randomNumeric(6) + "." + type;
    File destFile = new File(path);
    try {
        multipartFile.transferTo(destFile);
    } catch (IOException | IllegalStateException ex) {
        ex.printStackTrace();
    }
    //??(size)
    EasyImage easyImage = new EasyImage(path);

    request.setOrder(1);
    request.setMember(member);
    request.setWidth(easyImage.getWidth());
    request.setHeight(easyImage.getHeight());
    request.setSize(multipartFile.getSize());
    request.setTitle(multipartFile.getOriginalFilename());
    request.setSource(path);
    //        request.setDescription("?? ? setDescription");
    photosRequestService.create(request);

    return "/member/upload/result";
}

From source file:org.gallery.web.controller.FileController.java

@RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
public @ResponseBody Map upload(MultipartHttpServletRequest request, HttpServletResponse response) {

    log.info("uploadfile called...");
    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf;
    List<DataFileEntity> list = new LinkedList<>();

    while (itr.hasNext()) {
        mpf = request.getFile(itr.next());
        String originalFilename = mpf.getOriginalFilename();
        log.info("Uploading {}", originalFilename);

        String key = UUID.randomUUID().toString();
        String storageDirectory = fileUploadDirectory;

        File file = new File(storageDirectory + File.separatorChar + key);
        try {//from  w  w w . j  a  va  2s . co  m

            // Save Images
            mpf.transferTo(file);

            // Save FileEntity
            DataFileEntity dataFileEntity = new DataFileEntity();
            dataFileEntity.setName(mpf.getOriginalFilename());
            dataFileEntity.setKey(key);
            dataFileEntity.setSize(mpf.getSize());
            dataFileEntity.setContentType(mpf.getContentType());
            dataFileDao.save(dataFileEntity);
            list.add(dataFileEntity);
        } catch (IOException e) {
            log.error("Could not upload file " + originalFilename, e);
        }
    }
    Map<String, Object> files = new HashMap<>();
    files.put("files", list);
    return files;
}

From source file:mx.edu.um.mateo.inventario.web.ProductoController.java

@RequestMapping(value = "/crea", method = RequestMethod.POST)
public String crea(HttpServletRequest request, @Valid Producto producto, BindingResult bindingResult,
        Errors errors, Model modelo, RedirectAttributes redirectAttributes,
        @RequestParam(value = "imagen", required = false) MultipartFile archivo) {
    for (String nombre : request.getParameterMap().keySet()) {
        log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre));
    }/* w  ww .j  av  a 2  s.  c o  m*/
    if (bindingResult.hasErrors()) {
        log.debug("Hubo algun error en la forma, regresando");
        return "inventario/producto/nuevo";
    }

    try {

        if (archivo != null && !archivo.isEmpty()) {
            Imagen imagen = new Imagen(archivo.getOriginalFilename(), archivo.getContentType(),
                    archivo.getSize(), archivo.getBytes());
            producto.getImagenes().add(imagen);
        }
        Usuario usuario = ambiente.obtieneUsuario();
        producto = productoDao.crea(producto, usuario);

    } catch (ConstraintViolationException e) {
        log.error("No se pudo crear el producto", e);
        errors.rejectValue("nombre", "campo.duplicado.message", new String[] { "nombre" }, null);

        Map<String, Object> params = new HashMap<>();
        params.put("almacen", request.getSession().getAttribute("almacenId"));
        params.put("reporte", true);
        params = tipoProductoDao.lista(params);
        modelo.addAttribute("tiposDeProducto", params.get("tiposDeProducto"));

        return "inventario/producto/nuevo";
    } catch (IOException e) {
        log.error("No se pudo crear el producto", e);
        errors.rejectValue("imagenes", "problema.con.imagen.message",
                new String[] { archivo.getOriginalFilename() }, null);

        Map<String, Object> params = new HashMap<>();
        params.put("almacen", request.getSession().getAttribute("almacenId"));
        params.put("reporte", true);
        params = tipoProductoDao.lista(params);
        modelo.addAttribute("tiposDeProducto", params.get("tiposDeProducto"));

        return "inventario/producto/nuevo";
    }

    redirectAttributes.addFlashAttribute("message", "producto.creado.message");
    redirectAttributes.addFlashAttribute("messageAttrs", new String[] { producto.getNombre() });

    return "redirect:/inventario/producto/ver/" + producto.getId();
}

From source file:fr.mby.opa.pics.web.controller.UploadPicturesController.java

/***************************************************
 * URL: /upload/jqueryUpload upload(): receives files
 * /*from ww  w . j av a  2  s  . c o  m*/
 * @param request
 *            : MultipartHttpServletRequest auto passed
 * @param response
 *            : HttpServletResponse auto passed
 * @return LinkedList<FileMeta> as json format
 ****************************************************/
@ResponseBody
@RequestMapping(value = "/jqueryUpload", method = RequestMethod.POST)
public FileMetaList jqueryUpload(@RequestParam final Long albumId, final MultipartHttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    Assert.notNull(albumId, "No Album Id supplied !");

    final FileMetaList files = new FileMetaList();

    // 1. build an iterator
    final Iterator<String> itr = request.getFileNames();

    // 2. get each file
    while (itr.hasNext()) {

        // 2.1 get next MultipartFile
        final MultipartFile mpf = request.getFile(itr.next());

        // Here the file is uploaded

        final String originalFilename = mpf.getOriginalFilename();
        final String contentType = mpf.getContentType();

        final Matcher zipMatcher = UploadPicturesController.ZIP_CONTENT_TYPE_PATTERN.matcher(contentType);
        if (zipMatcher.find()) {

            // 2.3 create new fileMeta
            final FileMeta zipMeta = new FileMeta();
            zipMeta.setFileName(originalFilename);
            zipMeta.setFileSize(mpf.getSize() / 1024 + " Kb");
            zipMeta.setFileType(mpf.getContentType());

            final List<Path> picturesPaths = this.processArchive(mpf);

            final Collection<Future<Void>> futures = new ArrayList<>(picturesPaths.size());
            final ExecutorService executorService = Executors
                    .newFixedThreadPool(Runtime.getRuntime().availableProcessors());

            for (final Path picturePath : picturesPaths) {
                final Future<Void> future = executorService.submit(new Callable<Void>() {

                    @Override
                    public Void call() throws Exception {
                        final String pictureFileName = picturePath.getName(picturePath.getNameCount() - 1)
                                .toString();
                        final byte[] pictureContents = Files.readAllBytes(picturePath);

                        final FileMeta pictureMeta = new FileMeta();
                        try {
                            final Picture picture = UploadPicturesController.this.createPicture(albumId,
                                    pictureFileName.toString(), pictureContents);
                            final Long imageId = picture.getImage().getId();
                            final Long thumbnailId = picture.getThumbnail().getId();

                            pictureMeta.setFileName(pictureFileName);
                            pictureMeta.setFileSize(pictureContents.length / 1024 + " Kb");
                            pictureMeta.setFileType(Files.probeContentType(picturePath));
                            pictureMeta.setUrl(
                                    response.encodeURL(ImageController.IMAGE_CONTROLLER_PATH + "/" + imageId));
                            pictureMeta.setThumbnailUrl(response
                                    .encodeURL(ImageController.IMAGE_CONTROLLER_PATH + "/" + thumbnailId));
                        } catch (final PictureAlreadyExistsException e) {
                            // Picture already exists !
                            pictureMeta.setError(
                                    UploadPicturesController.PICTURE_ALREADY_EXISTS_MSG + e.getFilename());
                        } catch (final UnsupportedPictureTypeException e) {
                            // Picture already exists !
                            pictureMeta.setError(
                                    UploadPicturesController.UNSUPPORTED_PICTURE_TYPE_MSG + e.getFilename());
                        }

                        files.add(pictureMeta);

                        return null;
                    }
                });
                futures.add(future);
            }

            for (final Future<Void> future : futures) {
                future.get();
            }

            files.add(zipMeta);
        }

        final Matcher imgMatcher = UploadPicturesController.IMG_CONTENT_TYPE_PATTERN.matcher(contentType);
        if (imgMatcher.find()) {
            // 2.3 create new fileMeta
            final FileMeta fileMeta = new FileMeta();
            try {
                final byte[] fileContents = mpf.getBytes();
                final Picture picture = this.createPicture(albumId, originalFilename, fileContents);

                final Long imageId = picture.getImage().getId();
                final Long thumbnailId = picture.getThumbnail().getId();

                fileMeta.setFileName(originalFilename);
                fileMeta.setFileSize(mpf.getSize() / 1024 + " Kb");
                fileMeta.setFileType(mpf.getContentType());
                fileMeta.setBytes(fileContents);
                fileMeta.setUrl(response.encodeURL(ImageController.IMAGE_CONTROLLER_PATH + "/" + imageId));
                fileMeta.setThumbnailUrl(
                        response.encodeURL(ImageController.IMAGE_CONTROLLER_PATH + "/" + thumbnailId));

                // 2.4 add to files
                files.add(fileMeta);
            } catch (final PictureAlreadyExistsException e) {
                // Picture already exists !
                fileMeta.setError(UploadPicturesController.PICTURE_ALREADY_EXISTS_MSG);
            }
        }

    }

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

From source file:com.qcadoo.mes.cmmsMachineParts.controller.MachinePartMultiUploadController.java

@ResponseBody
@RequestMapping(value = "/multiUploadFiles", method = RequestMethod.POST)
public void upload(MultipartHttpServletRequest request, HttpServletResponse response) {
    Long part = Long.parseLong(request.getParameter("partId"));
    Entity technology = dataDefinitionService
            .get(BasicConstants.PLUGIN_IDENTIFIER, BasicConstants.MODEL_PRODUCT).get(part);
    DataDefinition attachmentDD = dataDefinitionService.get("cmmsMachineParts", "machinePartAttachment");

    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf = null;

    while (itr.hasNext()) {

        mpf = request.getFile(itr.next());

        String path = "";
        try {/*from  w ww.ja  va 2s. co m*/
            path = fileService.upload(mpf);
        } catch (IOException e) {
            logger.error("Unable to upload attachment.", e);
        }
        if (exts.contains(Files.getFileExtension(path).toUpperCase())) {
            Entity atchment = attachmentDD.create();
            atchment.setField(TechnologyAttachmentFields.ATTACHMENT, path);
            atchment.setField(TechnologyAttachmentFields.NAME, mpf.getOriginalFilename());
            atchment.setField("product", technology);
            atchment.setField(TechnologyAttachmentFields.EXT, Files.getFileExtension(path));
            BigDecimal fileSize = new BigDecimal(mpf.getSize(), numberService.getMathContext());
            BigDecimal divider = new BigDecimal(1024, numberService.getMathContext());
            BigDecimal size = fileSize.divide(divider, L_SCALE, BigDecimal.ROUND_HALF_UP);
            atchment.setField(TechnologyAttachmentFields.SIZE, size);
            atchment = attachmentDD.save(atchment);
            atchment.isValid();
        }
    }
}

From source file:com.qcadoo.mes.cmmsMachineParts.controller.MaintenanceEventMultiUploadController.java

@ResponseBody
@RequestMapping(value = "/multiUploadFilesForEvent", method = RequestMethod.POST)
public void upload(MultipartHttpServletRequest request, HttpServletResponse response) {
    Long eventId = Long.parseLong(request.getParameter("eventId"));
    Entity event = dataDefinitionService
            .get(CmmsMachinePartsConstants.PLUGIN_IDENTIFIER, CmmsMachinePartsConstants.MODEL_MAINTENANCE_EVENT)
            .get(eventId);//www  . j  a v a  2s  .c o  m
    DataDefinition attachmentDD = dataDefinitionService.get("cmmsMachineParts", "eventAttachment");

    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf = null;

    while (itr.hasNext()) {

        mpf = request.getFile(itr.next());

        String path = "";
        try {
            path = fileService.upload(mpf);
        } catch (IOException e) {
            logger.error("Unable to upload attachment.", e);
        }
        if (exts.contains(Files.getFileExtension(path).toUpperCase())) {
            Entity atchment = attachmentDD.create();
            atchment.setField(TechnologyAttachmentFields.ATTACHMENT, path);
            atchment.setField(TechnologyAttachmentFields.NAME, mpf.getOriginalFilename());
            atchment.setField("maintenanceEvent", event);
            atchment.setField(TechnologyAttachmentFields.EXT, Files.getFileExtension(path));
            BigDecimal fileSize = new BigDecimal(mpf.getSize(), numberService.getMathContext());
            BigDecimal divider = new BigDecimal(1024, numberService.getMathContext());
            BigDecimal size = fileSize.divide(divider, L_SCALE, BigDecimal.ROUND_HALF_UP);
            atchment.setField(TechnologyAttachmentFields.SIZE, size);
            atchment = attachmentDD.save(atchment);
            atchment.isValid();
        }
    }
}

From source file:com.qcadoo.mes.technologies.controller.TechnologyMultiUploadController.java

@ResponseBody
@RequestMapping(value = "/multiUploadFiles", method = RequestMethod.POST)
public void upload(MultipartHttpServletRequest request, HttpServletResponse response) {
    Long technologyId = Long.parseLong(request.getParameter("techId"));
    Entity technology = dataDefinitionService
            .get(TechnologiesConstants.PLUGIN_IDENTIFIER, TechnologiesConstants.MODEL_TECHNOLOGY)
            .get(technologyId);/*from ww w  .j av a 2s  .c o  m*/
    DataDefinition attachmentDD = dataDefinitionService.get(TechnologiesConstants.PLUGIN_IDENTIFIER,
            TechnologiesConstants.MODEL_TECHNOLOGY_ATTACHMENT);

    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf = null;

    while (itr.hasNext()) {

        mpf = request.getFile(itr.next());

        String path = "";
        try {
            path = fileService.upload(mpf);
        } catch (IOException e) {
            logger.error("Unable to upload attachment.", e);
        }
        if (exts.contains(Files.getFileExtension(path).toUpperCase())) {
            Entity atchment = attachmentDD.create();
            atchment.setField(TechnologyAttachmentFields.ATTACHMENT, path);
            atchment.setField(TechnologyAttachmentFields.NAME, mpf.getOriginalFilename());
            atchment.setField(TechnologyAttachmentFields.TECHNOLOGY, technology);
            atchment.setField(TechnologyAttachmentFields.EXT, Files.getFileExtension(path));
            BigDecimal fileSize = new BigDecimal(mpf.getSize(), numberService.getMathContext());
            BigDecimal divider = new BigDecimal(1024, numberService.getMathContext());
            BigDecimal size = fileSize.divide(divider, L_SCALE, BigDecimal.ROUND_HALF_UP);
            atchment.setField(TechnologyAttachmentFields.SIZE, size);
            attachmentDD.save(atchment);
        }
    }
}