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:eionet.webq.converter.MultipartFileToUserFileConverterTest.java

@Test
public void convertToUploadedFile() throws Exception {
    String schemaLocation = "testSchema";
    String rootAttributesDeclaration = rootAttributesDeclaration(noNamespaceSchemaAttribute(schemaLocation));
    byte[] fileContent = xmlWithRootElementAttributes(rootAttributesDeclaration);
    MultipartFile xmlFileUpload = createMultipartFile(fileContent);

    UserFile xmlFile = fileConverter.convert(xmlFileUpload).iterator().next();

    assertThat(xmlFile.getName(), equalTo(originalFilename));
    assertThat(xmlFile.getContent(), equalTo(fileContent));
    assertThat(xmlFile.getXmlSchema(), equalTo(schemaLocation));
    assertThat(xmlFile.getSizeInBytes(), equalTo(xmlFileUpload.getSize()));
}

From source file:com.glaf.template.web.springmvc.MxSystemTemplateController.java

@RequestMapping("/save")
public ModelAndView save(HttpServletRequest request, ModelMap modelMap) throws IOException {
    LoginContext loginContext = RequestUtils.getLoginContext(request);

    String templateId = request.getParameter("templateId");
    Template template = null;/*from   w  w  w.  java2s  .com*/
    if (StringUtils.isNotEmpty(templateId)) {
        template = templateService.getTemplate(templateId);
    }

    if (template == null) {
        template = new Template();
        template.setCreateBy(loginContext.getActorId());
    }

    MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
    Map<String, Object> paramMap = RequestUtils.getParameterMap(req);
    Tools.populate(template, paramMap);

    String nodeId = ParamUtils.getString(paramMap, "nodeId");
    if (nodeId != null) {

    }

    Map<String, MultipartFile> fileMap = req.getFileMap();
    Set<Entry<String, MultipartFile>> entrySet = fileMap.entrySet();
    for (Entry<String, MultipartFile> entry : entrySet) {
        MultipartFile mFile = entry.getValue();
        String filename = mFile.getOriginalFilename();
        if (mFile.getSize() > 0) {
            template.setFileSize(mFile.getSize());
            int fileType = 0;

            if (filename.endsWith(".java")) {
                fileType = 50;
                template.setContent(new String(mFile.getBytes()));
            } else if (filename.endsWith(".jsp")) {
                fileType = 51;
                template.setContent(new String(mFile.getBytes()));
            } else if (filename.endsWith(".ftl")) {
                fileType = 52;
                template.setLanguage("freemarker");
                template.setContent(new String(mFile.getBytes()));
            } else if (filename.endsWith(".vm")) {
                fileType = 54;
                template.setLanguage("velocity");
                template.setContent(new String(mFile.getBytes()));
            } else if (filename.endsWith(".xml")) {
                fileType = 60;
                template.setContent(new String(mFile.getBytes()));
            } else if (filename.endsWith(".htm") || filename.endsWith(".html")) {
                fileType = 80;
                template.setContent(new String(mFile.getBytes()));
            } else if (filename.endsWith(".js")) {
                fileType = 82;
                template.setContent(new String(mFile.getBytes()));
            } else if (filename.endsWith(".css")) {
                fileType = 84;
                template.setContent(new String(mFile.getBytes()));
            } else if (filename.endsWith(".txt")) {
                fileType = 85;
                template.setContent(new String(mFile.getBytes()));
            }

            template.setDataFile(filename);
            template.setFileType(fileType);
            template.setCreateDate(new Date());
            template.setData(mFile.getBytes());
            template.setLastModified(System.currentTimeMillis());
            template.setTemplateType(FileUtils.getFileExt(filename));
            break;
        }
    }

    templateService.saveTemplate(template);

    return this.list(request, modelMap);
}

From source file:controller.InternshipController.java

@RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.POST)
public String uploadMultipleFileHandler(@ModelAttribute("SpringWeb") docs.ApplicationModel application,
        ModelMap model, HttpSession session, @RequestParam("file") MultipartFile[] files) {

    if (session.getAttribute("userID") != null) {
        int idUser = (int) session.getAttribute("userID");
        STUDENTTYPE user = BusControl.getStudentbyId(idUser);

        application.setFirstName((String) user.getFIRSTNAME());
        application.setLastName((String) user.getLASTNAME());
        application.setMail((String) user.getMAIL());

        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];
            System.out.println("Taille : " + file.getSize());

            try {
                byte[] bytes = file.getBytes();
                file.getInputStream().read(bytes);
                System.out.println("URL retourne : " + BusControl.uploadCV(bytes));
                if (i == 0)
                    application.setCvPath(BusControl.uploadCV(bytes));
                if (i == 1)
                    application.setClPath(BusControl.uploadCV(bytes));
            } catch (Exception e) {
            }/*www . ja  v  a  2s . com*/
        }

        //Ajouter une application  la BD Entreprise
        int applicationID = BusControl.addNewApplicant(application);

        //Ajouter une application  la BD
        BusControl.createApplication(idUser, 3, applicationID, 0);

        //mise  jour de la liste de candidature
        APPLICATIONTYPE listCand = getApplications(idUser);
        ArrayList<Applications> listCan = new ArrayList<>();

        if (listCand != null) {
            Iterator<APPLICATION> ite = listCand.getAPPLICATIONS().iterator();
            while (ite.hasNext()) {
                APPLICATION offer = ite.next();
                InternshipCompanyModel inte = BusControl
                        .getOffersById(BusControl.getAppById(offer.getApplicationID()).getInternshipID());
                int statusId = BusControl.getAppById(offer.getApplicationID()).getStatus();
                String status = Utils.getStatus(statusId);
                COMPANYTYPE com = BusControl.getCompanybyId(offer.getCompanyID());

                Applications can = new Applications(offer.getApplicationID(), null, inte, com.getNOM(),
                        com.getMAIL(), com.getADDRESS(), status);
                if (statusId != 4) {
                    listCan.add(can);
                }

            }
        } else {
            listCan = null;
        }
        model.addAttribute("listCan", listCan);

        Utils.drawHomePage(session.getAttribute("userName").toString(),
                BusControl.getNotifications(idUser).getNOTIFS().size(), "searchStudent", "candidatureStudent",
                model);
        return "home";
    } else {
        model.addAttribute("errormessage", " You need to be authenticated. ");
        return "connection";
    }
}

From source file:cn.lhfei.fu.service.impl.HomeworkBaseServiceImpl.java

/**
 *  //from w  w w  .j a v a 2  s.c  o m
 * 
 * @see cn.lhfei.fu.service.HomeworkBaseService#update(cn.lhfei.fu.web.model.HomeworkBaseModel)
 */
@Override
public boolean update(HomeworkBaseModel model, String userType) throws NullPointerException {
    OutputStream out = null;
    BufferedOutputStream bf = null;
    Date currentTime = new Date();

    List<MultipartFile> files = model.getFiles();
    try {
        HomeworkBase base = homeworkBaseDAO.find(model.getBaseId());

        base.setModifyTime(currentTime);
        base.setActionType("" + OperationTypeEnum.SC.getCode());
        base.setOperationTime(currentTime);

        homeworkBaseDAO.save(base); // update homework_base info

        int num = 1;
        for (MultipartFile file : files) {// save archive file

            if (file.getSize() > 0) {
                String filePath = filePathBuilder.buildFullPath(model, model.getStudentName());
                String fileName = filePathBuilder.buildFileName(model, model.getStudentName(), num);

                String[] names = file.getOriginalFilename().split("[.]");

                String fileType = names[names.length - 1];

                String fullPath = filePath + File.separator + fileName + "." + fileType;

                out = new FileOutputStream(new File(fullPath));

                bf = new BufferedOutputStream(out);

                IOUtils.copyLarge(file.getInputStream(), bf);

                HomeworkArchive archive = new HomeworkArchive();
                archive.setArchiveName(fileName);
                archive.setArchivePath(fullPath);
                archive.setCreateTime(currentTime);
                archive.setModifyTime(currentTime);
                archive.setName(model.getName());
                archive.setStudentBaseId(model.getStudentBaseId());
                archive.setHomeworkBaseId(model.getBaseId());
                /*archive.setHomeworkBase(base);*/
                archive.setStudentName(model.getStudentName());
                archive.setStudentId(model.getStudentId());

                // ?
                if (userType != null && userType.equals(UserTypeEnum.STUDENT.getCode())) {
                    archive.setStatus("" + ApproveStatusEnum.DSH.getCode());
                } else if (userType != null && userType.equals(UserTypeEnum.TEACHER.getCode())) {
                    archive.setStatus("" + ApproveStatusEnum.DSH.getCode());
                } else if (userType != null && userType.equals(UserTypeEnum.ADMIN.getCode())) {
                    archive.setStatus("" + ApproveStatusEnum.YSH.getCode());
                }

                homeworkArchiveDAO.save(archive);

                // auto increment archives number.
                num++;
            }
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } catch (NullPointerException e) {
        log.error("File name arguments missed.", e);

        throw new NullPointerException(e.getMessage());
    } finally {
        if (out != null) {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
        if (bf != null) {
            try {
                bf.flush();
                bf.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    return false;
}

From source file:cs544.videohouse.validator.VideoConstraintValidator.java

@Override
public boolean isValid(MultipartFile video, ConstraintValidatorContext context) {
    System.out.println("inside video validation method");
    boolean valid = true;
    if (video.isEmpty()) {
        valid = false;//from w  w w.j ava  2s.c  om
    } else {
        String videoExt = FilenameUtils.getExtension(video.getOriginalFilename());
        if (!"mp4".equals(videoExt) && !"ogg".equals(videoExt) && !"ogv".equals(videoExt)
                && !"webM".equals(videoExt)) {
            valid = false;
        }
        long bytes = video.getSize();
        if (bytes > 20000000) {
            valid = false;
        }
        System.out.println("size : " + bytes);
    }
    return valid;
}

From source file:org.jasig.portlet.blackboardvcportlet.mvc.sessionmngr.SessionCreateEditController.java

@ActionMapping(params = "action=Upload Presentation")
public void uploadPresentation(ActionResponse response, Locale locale, @RequestParam long sessionId,
        @RequestParam MultipartFile presentationUpload, @RequestParam boolean needToSendInitialEmail)
        throws PortletModeException {
    String fileExtension = StringUtils.substringAfter(presentationUpload.getOriginalFilename(), ".")
            .toLowerCase();//  www.  j av a 2  s  .c  om

    // Validate
    if (presentationUpload.getSize() < 1) {
        response.setRenderParameter("presentationUploadError",
                messageSource.getMessage("error.uploadfilenotselected", null, locale));
    } else if (presentationUpload.getSize() > maxFileUploadSize) {
        response.setRenderParameter("presentationUploadError",
                messageSource.getMessage("error.uploadfilesizetoobig", null, locale));
    } else if (fileExtension.length() == 0 || !presentationFileTypes.contains(fileExtension)) {
        response.setRenderParameter("presentationUploadError",
                messageSource.getMessage("error.uploadfileextensionswrong", null, locale));
    } else {
        this.sessionService.addPresentation(sessionId, presentationUpload);
    }

    response.setPortletMode(PortletMode.VIEW);
    response.setRenderParameter("sessionId", Long.toString(sessionId));
    response.setRenderParameter("action", "viewSession");
    response.setRenderParameter("needToSendInitialEmail", Boolean.toString(needToSendInitialEmail));
}

From source file:br.edu.ifpb.controllers.TopicController.java

@RequestMapping(value = "/novoTopico", method = RequestMethod.POST)
public ModelAndView cadastrarNovoTopico(@Valid TopicValidator topicValidator, BindingResult result, Model model,
        @RequestParam("photo") MultipartFile file) {

    String name = topicValidator.getName();
    String description = topicValidator.getDescription();
    UserProfile userProfile = (UserProfile) httpSession.getAttribute("user");

    model.addAttribute("name", name);
    model.addAttribute("description", description);

    ModelAndView modelAndView = new ModelAndView("novoTopico");

    if (file.getSize() == 0) {
        model.addAttribute("erro", "Insira uma imagem para o tpico");
        result.addError(new ObjectError("erroImagem", "faltou inserir imagem"));
    }/*from w w w  .  ja  va 2 s.  c o  m*/

    if (result.hasErrors()) {
        return new ModelAndView("novoTopico");
    } else {

        Topic topic = topicoService.saveTopic(topicValidator.getName(), topicValidator.getDescription(),
                userProfile, file);
        if (topic != null) {

            //                modelAndView.getModel().put("succes", true);
            modelAndView = new ModelAndView("novoTopicoSuccess");
            modelAndView.addObject("id", topic.getId());

        }

    }

    return modelAndView;
}

From source file:org.opentides.web.validator.ImageValidator.java

@Override
public void validate(Object obj, Errors errors) {
    AjaxUpload ajaxUpload = (AjaxUpload) obj;
    MultipartFile attachment = ajaxUpload.getAttachment();
    ValidationUtils.rejectIfEmpty(errors, "attachment", "photo.image-required");
    if (attachment != null && !attachment.isEmpty()) {
        String contentType = attachment.getContentType().substring(0, 6);
        if (!"image/".equals(contentType)) {
            errors.rejectValue("attachment", "photo.invalid-file-type",
                    "Invalid file. Profile Image must be in PNG, JPEG, GIF or BMP format.");
        } else if (attachment.getSize() > 1024 * 1024 * 10) {
            errors.rejectValue("attachment", "photo.invalid-file-size",
                    "Invalid file. Maximum file size is 10 Megabytes");
        }//www. j  av  a2  s.  c  o  m
    }

}

From source file:com.orchestra.portale.controller.UserEditController.java

@RequestMapping(value = "userEditProfile", method = RequestMethod.POST)
@Secured("ROLE_USER")
public ModelAndView updateUser(HttpServletRequest request, @ModelAttribute("SpringWeb") User user,
        MultipartFile avatar) {
    ModelAndView model = new ModelAndView("userInfo");
    User olduser = pm.findUserByUsername(user.getUsername());
    user.setId(olduser.getId());/*from  ww w  .j  av a  2  s .  com*/

    if (user.getPassword() == null || user.getPassword().equals("")) {
        user.setPassword(olduser.getPassword());
    } else {
        user.setPassword(crypt(user.getPassword()));
    }

    pm.saveUser(user);

    if (avatar.getSize() > 0) {

        User user2 = pm.findUserByUsername(user.getUsername());
        MultipartFile file = avatar;

        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            HttpSession session = request.getSession();
            ServletContext sc = session.getServletContext();

            File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "user" + File.separator + "img"
                    + File.separator + user2.getId());
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + "avatar.jpg");
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();
        } catch (Exception e) {

        }

    }
    model.addObject("user", user);
    HttpSession session = request.getSession();
    ServletContext sc = session.getServletContext();
    File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "user" + File.separator + "img"
            + File.separator + user.getId() + File.separator + "avatar.jpg");
    if (dir.exists()) {
        model.addObject("avatar", "./dist/user/img/" + user.getId() + "/avatar.jpg");
    } else {
        model.addObject("avatar", "./dist/img/default_avatar.png");
    }
    return model;
}

From source file:com.denimgroup.threadfix.importer.loader.ScanTypeCalculationServiceImpl.java

private void checkDiskSpace(MultipartFile file) {
    long usableSpace = DiskUtils.getAvailableDiskSpace();

    long size = file.getSize();

    String sizeMessage = "need " + size + " bytes to write file, " + usableSpace + " available.";

    if (size > usableSpace) {
        log.error("Not enough space to write temporary scan file: " + sizeMessage);
        throw new RestIOException("Not enough disk space to store temporary scan file.", 200);
    } else {/*from   w w  w . java2  s.  c o m*/
        log.debug("Should have enough room: " + sizeMessage);
    }
}