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.davidmendoza.fileUpload.web.VideoController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody Map upload(MultipartHttpServletRequest request, HttpServletResponse response) {
    log.debug("upload Post called");
    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf;
    List<Video> list = new LinkedList<>();

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

        String newFilenameBase = UUID.randomUUID().toString();
        String originalFileExtension = mpf.getOriginalFilename()
                .substring(mpf.getOriginalFilename().lastIndexOf("."));
        String newFilename = newFilenameBase + originalFileExtension;
        String storageDirectory = getRealPath(request);
        String contentType = mpf.getContentType();

        File newFile = new File(storageDirectory + "/" + newFilename);
        try {/*from  w ww  . j  a  v a2 s. c  om*/
            mpf.transferTo(newFile);

            Video video = new Video();
            video.setName(mpf.getOriginalFilename());
            video.setNewFilename(newFilename);
            video.setContentType(contentType);
            video.setSize(mpf.getSize());
            video = videoDao.create(video);

            video.setDeleteUrl("/video/delete/" + video.getId());
            video.setDeleteType("DELETE");

            list.add(video);

        } catch (IOException e) {
            log.error("Could not upload file " + mpf.getOriginalFilename(), e);
        }

    }

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

From source file:com.siblinks.ws.service.impl.PlaylistServiceImpl.java

/**
 * {@inheritDoc}//from   w w w .  ja va2s  . c o  m
 */
private String uploadPlaylistThumbnail(final MultipartFile image) throws Exception {
    String fullPath = "";
    String filename = "";
    String name;
    String filepath = "";
    String directory = environment.getProperty("directoryPlaylistImage");
    String service = environment.getProperty("directoryGetPlaylistImage");
    String strExtenstionFile = environment.getProperty("file.upload.image.type");
    String limitSize = environment.getProperty("file.upload.essay.size");

    if (image != null) {
        name = image.getOriginalFilename();
        String nameExt = FilenameUtils.getExtension(name);
        boolean status = strExtenstionFile.contains(nameExt.toLowerCase());
        if (image.getSize() > Long.parseLong(limitSize)) {
            throw new Exception("Thumbnail maximum is 5MB.");
        } else {
            BufferedOutputStream stream = null;
            if (directory != null && status) {
                try {
                    RandomString randomName = new RandomString();
                    filename = randomName.random() + "." + "png";

                    filepath = "" + Paths.get(directory, filename);
                    // Save the file locally
                    File file = new File(filepath);
                    File parentDir = file.getParentFile();
                    if (!parentDir.exists()) {
                        parentDir.mkdirs();
                    }
                    stream = new BufferedOutputStream(new FileOutputStream(file));
                    stream.write(image.getBytes());

                    fullPath = service + filename;
                } catch (Exception e) {
                    throw new Exception("Upload playlist thumbnail failed");
                } finally {
                    if (stream != null) {
                        stream.close();
                    }
                }
            }
        }
    } else {
        throw new Exception("Please select playlist thumbnail.");
    }

    return fullPath;
}

From source file:seava.j4e.web.controller.upload.FileUploadController.java

/**
 * Generic file upload. Expects an uploaded file and a handler alias to
 * delegate the uploaded file processing.
 * // w  w  w .  j av  a2s.com
 * @param handler
 *            spring bean alias of the
 *            {@link seava.j4e.api.service.IFileUploadService} which should
 *            process the uploaded file
 * @param file
 *            Uploaded file
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/{handler}", method = RequestMethod.POST)
@ResponseBody
public String fileUpload(@PathVariable("handler") String handler, @RequestParam("file") MultipartFile file,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    try {
        if (logger.isInfoEnabled()) {
            logger.info("Processing file upload request with-handler {} ", new Object[] { handler });
        }

        if (file.isEmpty()) {
            throw new BusinessException(ErrorCode.G_FILE_NOT_UPLOADED,
                    "Upload was not succesful. Try again please.");
        }

        this.prepareRequest(request, response);

        IFileUploadService srv = this.getFileUploadService(handler);
        Map<String, String> paramValues = new HashMap<String, String>();

        for (String p : srv.getParamNames()) {
            paramValues.put(p, request.getParameter(p));
        }

        IUploadedFileDescriptor fileDescriptor = new UploadedFileDescriptor();
        fileDescriptor.setContentType(file.getContentType());
        fileDescriptor.setOriginalName(file.getOriginalFilename());
        fileDescriptor.setNewName(file.getName());
        fileDescriptor.setSize(file.getSize());
        Map<String, Object> result = srv.execute(fileDescriptor, file.getInputStream(), paramValues);

        result.put("success", true);
        ObjectMapper mapper = getJsonMapper();
        return mapper.writeValueAsString(result);
    } catch (Exception e) {
        return this.handleManagedException(null, e, response);
    } finally {
        this.finishRequest();
    }

}

From source file:com.virtusa.akura.staff.controller.StaffDetailsController.java

/**
 * loads the image from given image file.
 * /*from   w w  w  .  j  ava 2  s. com*/
 * @param staff - Staff
 * @throws IOException - detail exception during file processing
 */
private void uploadImage(Staff staff) throws IOException {

    if (staff.getMultipartFile() != null) {
        MultipartFile multipartFile = staff.getMultipartFile();
        if (multipartFile.getSize() > 0) {
            staff.setPhoto(multipartFile.getBytes());
        }

    }
}

From source file:com.virtusa.akura.staff.controller.StaffDetailsController.java

/**
 * Updates the staff Details./* w  w  w.ja  va  2  s .c  om*/
 * 
 * @param staff the staff.
 * @param model the model.
 * @param request the request
 * @return the return path.
 * @throws AkuraAppException AkuraAppException.
 * @throws IOException IOException.
 */
private String updateStaffDetails(Staff staff, ModelMap model, HttpServletRequest request)
        throws AkuraAppException, IOException {

    Staff staffObjDb = staffService.findStaff(staff.getStaffId());

    if (staff.getMultipartFile() != null) {
        MultipartFile multipartFile = staff.getMultipartFile();
        if (multipartFile.getSize() > 0) {
            staff.setPhoto(multipartFile.getBytes());
        } else {
            if (staffObjDb.getPhoto() != null && staffObjDb.getPhoto().length > 0) {
                staff.setPhoto(staffObjDb.getPhoto());
            }
        }

    }

    staffService.modifyStaff(staff);

    // Update end date in section head when update the date of departure.
    if (staff.getDateOfDeparture() != null) {
        updateEndDateForDepartureStaff(staff.getStaffId(), staff.getDateOfDeparture());
    }

    // Update if user login exist for this staff.
    UserLogin userLogin = userService.getUserLoginByIdentificationNo(staff.getRegistrationNo());
    if (userLogin != null) {
        userLogin.setUserIdentificationNo(staff.getRegistrationNo());
        userService.updateUser(userLogin);
    }
    String message = new ErrorMsgLoader().getErrorMessage(MESSAGE_RECORD_MODIFIED);
    model.addAttribute(MESSAGE, message);
    model.addAttribute(MODEL_ATT_STAFF, staff);
    return loadStaffDetails(request, model, request.getSession());
}

From source file:kr.co.exsoft.external.controller.ExternalPublicController.java

@RequestMapping(value = "/restful.postwithfile", method = RequestMethod.POST)
@ResponseBody/* www.j a v  a 2  s  .c  o m*/
//public List<HashMap<String,Object>> uploadMultipleFileHandler(
public Map<String, Object> uploadMultipleFileHandler(@RequestHeader HashMap<String, Object> headMap,
        @RequestParam HashMap<String, Object> paraMap, @RequestParam("fileUpload") MultipartFile[] files,
        HttpServletRequest request) throws IllegalStateException, IOException {

    System.out.println("=============================");
    System.out.println(paraMap.get("folderPath").toString());
    System.out.println("=============================");

    //List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>();
    Map<String, Object> list = new HashMap<String, Object>();
    Map<String, Object> pagelist = new HashMap<String, Object>();
    HashMap<String, Object> resultMap = new HashMap<String, Object>();

    Map<String, Object> resultDBMap = new HashMap<String, Object>();
    PageVO pageVO = new PageVO();
    PageDao pageDao = sqlSession.getMapper(PageDao.class);

    String orgFileName = "";
    long fileSize = 0L;

    EXrepClient eXrepClient = new EXrepClient();
    List<HashMap<String, Object>> pageIds = new ArrayList<HashMap<String, Object>>();
    HashMap<String, Object> resultData = null;
    int cnt = 0;
    if (null != files && files.length > 0) {
        for (MultipartFile multipartFile : files) {
            cnt++;
            orgFileName = multipartFile.getOriginalFilename();//? ?
            fileSize = multipartFile.getSize();//? ? ?

            String contentPath = "";
            // try {
            //eXrepClient.connect();
            //contentPath = CommonUtil.getContentPathByDate(ConfigData.getString(Constant.EXREP_ROOT_EDMS_NM))+UUID.randomUUID().toString();

            //if(eXrepClient.putFile(new SizedInputStream(multipartFile.getInputStream(), fileSize),ConfigData.getString(Constant.EXREP_VOLUME_NM), contentPath,true)) {                              
            // 
            //   resultDBMap.put("result", "success");
            //}
            //} catch (ExrepClientException e) {
            // TODO Auto-generated catch block
            //
            //   resultDBMap.put("result", "fail");

            //   e.printStackTrace();
            //}

            //? ?  
            try {
                pageVO.setPage_id(CommonUtil.getStringID(Constant.ID_PREFIX_PAGE,
                        commonService.commonNextVal(Constant.COUNTER_ID_PAGE)));

                //json? DB? ?? PageId 
                resultData = new HashMap<String, Object>();
                resultData.put("stephan", "1234kb" + String.valueOf(cnt));
                resultData.put("pageId" + String.valueOf(cnt), pageVO.getPage_id());
                //list.add(resultData);   
                pageIds.add(resultData);

                //list.put("pageId"+String.valueOf(cnt),pageVO.getPage_id());

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

            //PAGE  
            pageVO.setPage_name(orgFileName);
            pageVO.setPage_extension(
                    orgFileName.substring(orgFileName.lastIndexOf(".") + 1, orgFileName.length())); // ? ?
            pageVO.setVolume_id(ConfigData.getString(Constant.EXREP_VOLUME_NM));
            pageVO.setContent_path(contentPath);
            pageVO.setPage_size(fileSize);

            int result = 0;
            result = pageDao.writePage(pageVO);
            if (result == 0) {
                System.out.println("XR_PAGE DB INSERT FAIL");
            } else {
                System.out.println("XR_PAGE DB INSERT SUCCESS");
            }

            /*if (!"".equalsIgnoreCase(orgFileName)) {
            // Handle file content - multipartFile.getInputStream()
            multipartFile.transferTo(new File(saveDirectory + orgFileName));
            fileNames.add(orgFileName);
            }*/

        }

        list.put("pageIds", pageIds);

    } else {
        //resultMap.put("result", "File not found");
        //list.add(resultMap);
        list.put("result", "File not found");
        return list;
    }

    //resultMap.put("result", "SUCCESS");
    //list.add(resultMap); 
    list.put("result", "SUCCESS");
    return list;

}

From source file:fr.univrouen.poste.web.candidat.MyPosteCandidatureController.java

@RequestMapping(value = "/{id}/addMemberReviewFile", method = RequestMethod.POST, produces = "text/html")
@PreAuthorize("hasPermission(#id, 'review')")
public String addMemberReviewFile(@PathVariable("id") Long id, @Valid MemberReviewFile memberReviewFile,
        BindingResult bindingResult, Model uiModel, HttpServletRequest request) throws IOException {
    if (bindingResult.hasErrors()) {
        logger.warn(bindingResult.getAllErrors());
        return "redirect:/postecandidatures/" + id.toString();
    }/*ww  w . j  a v  a  2  s.c  om*/
    uiModel.asMap().clear();

    // get PosteCandidature from id
    PosteCandidature postecandidature = PosteCandidature.findPosteCandidature(id);

    // upload file
    MultipartFile file = memberReviewFile.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();
        Long fileSize = file.getSize();

        boolean filenameAlreadyUsed = false;
        for (MemberReviewFile rFile : postecandidature.getMemberReviewFiles()) {
            if (rFile.getFilename().equals(filename)) {
                filenameAlreadyUsed = true;
                break;
            }
        }

        if (filenameAlreadyUsed) {
            uiModel.addAttribute("filename_already_used", filename);
            logger.info("addMemberReviewFile - upload restriction sur '" + filename
                    + "' un fichier de mme nom existe dj pour une candidature de "
                    + postecandidature.getCandidat().getEmailAddress());
        } else {

            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(":.*", "");

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

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

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

                User currentUser = getCurrentUser();
                memberReviewFile.setMember(currentUser);

                postecandidature.getMemberReviewFiles().add(memberReviewFile);

                //postecandidature.setModification(currentTime);

                postecandidature.persist();

                logService.logActionFile(LogService.UPLOAD_REVIEW_ACTION, postecandidature, memberReviewFile,
                        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:/postecandidatures/" + id.toString();
}

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

@RequestMapping(value = "/s/admin/{eventKey}/speaker/{speakerId}", method = RequestMethod.POST)
public String editSpeaker(@PathVariable("eventKey") String eventKey, @PathVariable("speakerId") Long speakerId,
        @RequestParam MultipartFile pictureFile, @Valid Speaker speakerForm, BindingResult result,
        HttpServletRequest request, ModelMap model, RedirectAttributes redirectAttributes) {

    if (request.getParameter("cancel") != null) {
        return "redirect:/s/admin/{eventKey}/speakers";
    }//ww w .j a  v a 2s.  c o m

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

    final Speaker speakerFromDb = businessService.getSpeakerWithPicture(speakerId);

    speakerFromDb.setBio(speakerForm.getBio());
    speakerFromDb.setTwitterId(speakerForm.getTwitterId());
    speakerFromDb.setGooglePlusId(speakerForm.getGooglePlusId());
    speakerFromDb.setLinkedInId(speakerForm.getLinkedInId());
    speakerFromDb.setLanyrdId(speakerForm.getLanyrdId());
    speakerFromDb.setGithubId(speakerForm.getGithubId());

    speakerFromDb.setFirstName(speakerForm.getFirstName());
    speakerFromDb.setLastName(speakerForm.getLastName());
    speakerFromDb.setCompany(speakerForm.getCompany());

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

        final FileData pictureData;
        if (speakerFromDb.getPicture() == null) {
            pictureData = new FileData();
        } else {
            pictureData = speakerFromDb.getPicture();
        }

        try {

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

        } catch (IOException e) {
            throw new IllegalStateException(e);
        }

        speakerFromDb.setPicture(pictureData);

    }

    businessService.saveSpeaker(speakerFromDb);

    redirectAttributes.addFlashAttribute("successMessage",
            String.format("The speaker '%s' was edited successfully.", speakerFromDb.getFirstLastName()));

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

From source file:com.zhenhappy.ems.action.user.VisaAction.java

@RequestMapping(value = "/visa/saveVisa", method = RequestMethod.POST)
public ModelAndView saveVisa(@ModelAttribute(Principle.PRINCIPLE_SESSION_ATTRIBUTE) Principle principle,
        @ModelAttribute SaveVisaInfoRequest visa,
        @RequestParam(value = "license", required = false) MultipartFile license,
        @RequestParam(value = "passportPageFile", required = false) MultipartFile passportPage) {
    ModelAndView modelAndView = new ModelAndView("/user/callback");
    try {/*ww  w. j  a va 2  s .  co m*/
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (StringUtils.isNotEmpty(visa.getBirthDay())) {
            visa.setBirth(sdf.parse(visa.getBirthDay()));
        }
        if (StringUtils.isNotEmpty(visa.getFromDate())) {
            visa.setFrom(sdf.parse(visa.getFromDate()));
        }
        if (StringUtils.isNotEmpty(visa.getToDate())) {
            visa.setTo(sdf.parse(visa.getToDate()));
        }
        if (StringUtils.isNotEmpty(visa.getExpireDate())) {
            visa.setExpDate(sdf.parse(visa.getExpireDate()));
        }
        if (license != null) {
            String fileName = systemConfig.getVal(Constants.appendix_directory) + "/" + new Date().getTime()
                    + "." + FilenameUtils.getExtension(license.getOriginalFilename());
            if (license != null && license.getSize() != 0) {
                FileUtils.copyInputStreamToFile(license.getInputStream(), new File(fileName));
                visa.setBusinessLicense(fileName);
            }
        }

        if (passportPage != null) {
            String fileName = systemConfig.getVal(Constants.appendix_directory) + "/" + new Date().getTime()
                    + "." + FilenameUtils.getExtension(passportPage.getOriginalFilename());
            if (passportPage != null && passportPage.getSize() != 0) {
                FileUtils.copyInputStreamToFile(passportPage.getInputStream(), new File(fileName));
                visa.setPassportPage(fileName);
            }
        }
        visa.setEid(principle.getExhibitor().getEid());
        TVisa temp = new TVisa();
        BeanUtils.copyProperties(visa, temp);
        visaService.saveOrUpdate(temp);
        modelAndView.addObject("method", "addSuccess");
    } catch (Exception e) {
        log.error("add visa error", e);
        modelAndView.addObject("method", "addFailure");
    }
    return modelAndView;
}