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:org.chimi.s4s.controller.FileUploadController.java

private UploadResult saveTemporaryFileToFileService(MultipartFile userUploadFile, String serviceId,
        String fileName, String mimeType, File tempFile) {
    UploadFile uf = new UploadFile(serviceId, fileName, mimeType, tempFile, userUploadFile.getSize());
    UploadResult uploadResult = fileService.save(uf);
    return uploadResult;
}

From source file:fr.esiea.esieaddress.controllers.importation.CSVImportCtrl.java

@RequestMapping(method = RequestMethod.POST)
@ResponseBody//from  w  w w  . j ava 2  s  . c  om
@Secured("ROLE_USER")
public void upload(MultipartHttpServletRequest files, final HttpServletRequest request)
        throws DaoException, ServiceException, FileNotFoundException {
    LOGGER.info("[IMPORT] Start to import contact");

    //TODO Make it less verbose and may use a buffer to make it safer
    Map<String, MultipartFile> multipartFileMap = files.getMultiFileMap().toSingleValueMap();
    Set<String> fileNames = multipartFileMap.keySet();

    for (String fileName : fileNames) {

        MultipartFile multipartFile = multipartFileMap.get(fileName);
        String originalFilename = multipartFile.getOriginalFilename();

        if (checkFileName(originalFilename) && multipartFile.getSize() < FILE_SIZE_MAX) {

            InputStream inputStream = null;

            try {
                inputStream = multipartFile.getInputStream();
            } catch (IOException e) {
                throw new FileNotFoundException(e.toString());
            }

            try (Reader contactsFile = new InputStreamReader(inputStream)) {
                Map<String, Object> modelErrors = new HashMap<>();
                LOGGER.debug("[IMPORT] File is reading");
                Collection<Contact> contacts = csvService.ReadContactCSV(contactsFile);
                for (Contact contact : contacts) {
                    try {
                        contactCrudService.insert(contact);
                    } catch (ValidationException e) {
                        Object modelError = e.getModel();
                        LOGGER.warn("found an error in contact " + modelError);
                        modelErrors.put(contact.getId(), (Map) modelError);
                    }
                }

                if (!modelErrors.isEmpty())
                    throw new ValidationException(modelErrors);
            } catch (IOException e) {
                throw new FileNotFoundException(e.toString());
            } finally {
                if (inputStream != null)
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        LOGGER.error("[IMPORT] Impossible to close the file " + inputStream.toString());
                    }
            }
        }
    }
}

From source file:org.pdfgal.pdfgalweb.validators.utils.impl.ValidatorUtilsImpl.java

@Override
public void validateFile(final MultipartFile file, final Errors errors,
        final PDFEncryptionType pdfEncryptionType) {

    if (file == null || file.getSize() == 0) {
        errors.rejectValue("file", "common.validator.file.required");

    } else {//w ww . j  av a 2 s  .c om
        final PDFEncryptionType validation = this.validatePDF(file);
        if (PDFEncryptionType.NON_PDF.equals(validation)) {
            errors.rejectValue("file", "common.validator.file.incorrect.pdf");

        } else if (!validation.equals(pdfEncryptionType)) {

            if (PDFEncryptionType.NON_ENCRYPTED.equals(pdfEncryptionType)) {
                errors.rejectValue("file", "common.validator.file.incorrect.encrypted.true");
            } else if (PDFEncryptionType.ENCRYPTED.equals(pdfEncryptionType)) {
                errors.rejectValue("file", "common.validator.file.incorrect.encrypted.false");
            }
        }
    }
}

From source file:feign.form.Server.java

@RequestMapping(value = "/upload/{id}", method = POST)
@ResponseStatus(OK)/*from   www. j  a v  a2s. co  m*/
public ResponseEntity<Long> upload(@PathVariable("id") Integer id, @RequestParam("public") Boolean isPublic,
        @RequestParam("file") MultipartFile file) {
    HttpStatus status;
    if (id == null || id != 10) {
        status = LOCKED;
    } else if (isPublic == null || !isPublic) {
        status = FORBIDDEN;
    } else if (file.getSize() == 0) {
        status = I_AM_A_TEAPOT;
    } else if (file.getOriginalFilename() == null || file.getOriginalFilename().trim().isEmpty()) {
        status = CONFLICT;
    } else {
        status = OK;
    }
    return ResponseEntity.status(status).body(file.getSize());
}

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

@Override
public OperationCompletionRS uploadPhoto(String username, MultipartFile file) {
    try {/*from  w w  w .  ja  v  a  2s  .co  m*/
        validatePhoto(file);
        BinaryData binaryData = new BinaryData(file.getContentType(), file.getSize(), file.getInputStream());
        userRepository.replaceUserPhoto(username, binaryData);
    } catch (IOException e) {
        fail().withError(BINARY_DATA_CANNOT_BE_SAVED);
    }
    return new OperationCompletionRS("Profile photo has been uploaded successfully");
}

From source file:com.glaf.jbpm.web.springmvc.MxJbpmDeployController.java

@RequestMapping(value = "/reconfig", method = RequestMethod.POST)
public ModelAndView reconfig(HttpServletRequest request) {
    String actorId = RequestUtils.getActorId(request);
    String archive = request.getParameter("archive");
    if (LogUtils.isDebug()) {
        logger.debug("deploying archive " + archive);
    }/*from   w w  w.  j a  va2s  . c  o  m*/
    MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
    JbpmExtensionReader reader = new JbpmExtensionReader();
    JbpmContext jbpmContext = null;
    try {
        jbpmContext = ProcessContainer.getContainer().createJbpmContext();
        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) {
                List<Extension> extensions = reader.readTasks(mFile.getInputStream());
                if (extensions != null && extensions.size() > 0) {
                    Iterator<Extension> iter = extensions.iterator();
                    while (iter.hasNext()) {
                        Extension extension = iter.next();
                        extension.setCreateActorId(actorId);
                    }
                    JbpmExtensionManager jbpmExtensionManager = ProcessContainer.getContainer()
                            .getJbpmExtensionManager();
                    jbpmExtensionManager.reconfig(jbpmContext, extensions);
                    request.setAttribute("message", "???");
                }
            }
        }
    } catch (Exception ex) {
        if (jbpmContext != null) {
            jbpmContext.setRollbackOnly();
        }
        request.setAttribute("error_code", 9913);
        request.setAttribute("error_message", "");
        return new ModelAndView("/error");
    } finally {
        Context.close(jbpmContext);
    }

    String jx_view = request.getParameter("jx_view");

    if (StringUtils.isNotEmpty(jx_view)) {
        return new ModelAndView(jx_view);
    }

    String x_view = ViewProperties.getString("jbpm_deploy.configFinish");
    if (StringUtils.isNotEmpty(x_view)) {
        return new ModelAndView(x_view);
    }

    return new ModelAndView("/jbpm/deploy/configFinish");
}

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

@RequestMapping
public void upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
    response.setContentType("text/html; charset=UTF-8");
    String businessKey = request.getParameter("businessKey");
    String serviceKey = request.getParameter("serviceKey");
    // ?/*from  w  ww.j  av a2  s .  co m*/
    LoginContext loginContext = RequestUtils.getLoginContext(request);
    String savePath = SystemProperties.getAppPath() + "/upload/" + loginContext.getUser().getId() + "/";
    // ?URL
    String saveUrl = request.getContextPath() + "/upload/" + loginContext.getUser().getId() + "/";
    if (StringUtils.isNotEmpty(serviceKey)) {
        saveUrl = saveUrl + serviceKey + "/";
    }
    // ???
    String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp", "swf" };
    // ?
    long maxSize = 10240000;

    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);
    }

    // 
    File uploadDir = new File(savePath);
    try {
        if (!uploadDir.exists()) {
            FileUtils.mkdirs(savePath);
        }
    } catch (Exception ex) {
    }

    if (!uploadDir.isDirectory()) {
        response.getWriter().write(getError("?"));
        return;
    }
    // ??
    if (!uploadDir.canWrite()) {
        response.getWriter().write(getError("??"));
        return;
    }

    MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
    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.setFilename(fileName);
                dataFile.setType(fileExt);
                dataFile.setSize(mFile.getSize());
                dataFile.setStatus(1);
                blobService.insertBlob(dataFile);

                FileUtils.save(savePath + sp + newFileName, mFile.getInputStream());

            } catch (Exception ex) {
                ex.printStackTrace();
                response.getWriter().write(getError("?"));
                return;
            }

            JSONObject object = new JSONObject();
            object.put("error", 0);
            object.put("url", saveUrl + newFileName);
            response.getWriter().write(object.toString());
        }
    }
}

From source file:com.glaf.jbpm.web.springmvc.MxJbpmDeployController.java

@RequestMapping(value = "/deploy", method = RequestMethod.POST)
public ModelAndView deploy(HttpServletRequest request, HttpServletResponse response) {
    String archive = request.getParameter("archive");
    if (LogUtils.isDebug()) {
        logger.debug("deploying archive " + archive);
    }//from w ww .  java 2s . c o  m

    MxJbpmProcessDeployer deployer = new MxJbpmProcessDeployer();

    byte[] bytes = null;
    JbpmContext jbpmContext = null;
    try {
        jbpmContext = ProcessContainer.getContainer().createJbpmContext();

        if (jbpmContext != null && jbpmContext.getSession() != null) {
            MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
            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) {
                    ProcessDefinition processDefinition = deployer.deploy(jbpmContext, mFile.getBytes());
                    bytes = processDefinition.getFileDefinition().getBytes("processimage.jpg");
                    response.setContentType("image/jpeg");
                    response.setHeader("Pragma", "No-cache");
                    response.setHeader("Expires", "-1");
                    response.setHeader("ICache-Control", "no-cache");
                    response.setDateHeader("Expires", 0L);
                    OutputStream out = response.getOutputStream();
                    out.write(bytes);
                    out.flush();
                    out.close();
                    bytes = null;
                    return null;
                }
            }
        }
    } catch (JbpmException ex) {
        if (jbpmContext != null) {
            jbpmContext.setRollbackOnly();
        }
        request.setAttribute("error_code", 9912);
        request.setAttribute("error_message", "");
        return new ModelAndView("/error");
    } catch (IOException ex) {
        if (jbpmContext != null) {
            jbpmContext.setRollbackOnly();
        }
        request.setAttribute("error_code", 9912);
        request.setAttribute("error_message", "");
        return new ModelAndView("/error");
    } finally {
        Context.close(jbpmContext);
        bytes = null;
    }
    return null;
}

From source file:org.openmrs.module.drawing.web.controller.ManageTemplatesController.java

@RequestMapping(value = "/module/drawing/manageTemplates", method = RequestMethod.POST)
public void manage(@RequestParam(value = "templateName", required = false) String templateName,
        @RequestParam(value = "template", required = true) MultipartFile file, ModelMap model,
        HttpSession session) {/*w  w  w  .  jav  a 2  s. c o  m*/

    model.addAttribute("encodedTemplateNames", DrawingUtil.getAllTemplateNames());
    if (file == null || file.getSize() == 0) {
        session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Please Fill All The Fields");
        return;
    } else if (!DrawingUtil.isImage(file.getOriginalFilename())) {
        session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "File Format Not Supported");
        return;
    }
    if (StringUtils.isBlank(templateName))
        templateName = file.getOriginalFilename();
    else
        templateName = templateName + "." + DrawingUtil.getExtension(file.getOriginalFilename());

    try {
        BufferedImage bi = ImageIO.read(new ByteArrayInputStream(file.getBytes()));
        Boolean saved = DrawingUtil.saveFile(templateName, bi);
        if (saved) {
            session.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Template Saved");
            model.addAttribute("encodedTemplateNames", DrawingUtil.getAllTemplateNames());

        } else
            session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Error Saving Template");

    } catch (IOException e) {
        session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Unable To Save Uploaded File");
        log.error("Unable to read uploadedFile", e);
    }

}