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:uk.urchinly.wabi.ingest.UploadController.java

@RequestMapping(method = RequestMethod.POST, value = "/upload")
public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) {

    if (file.isEmpty()) {
        logger.debug("Upload file is empty.");
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Failed with empty file");
    }/*from  www. j a  v  a2  s . com*/

    BufferedOutputStream outputStream = null;

    try {
        File outputFile = new File(appSharePath + "/" + file.getOriginalFilename());
        outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

        FileCopyUtils.copy(file.getInputStream(), outputStream);

        Asset asset = new Asset(file.getOriginalFilename(), file.getOriginalFilename(), (double) file.getSize(),
                file.getContentType(), Collections.emptyList());

        this.saveAsset(asset);
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Failed with error");
    } finally {
        IOUtils.closeQuietly(outputStream);
    }

    return ResponseEntity.ok("File accepted");
}

From source file:cz.zcu.kiv.eegdatabase.webservices.rest.scenario.ScenarioServiceController.java

/**
 * Creates new scenario record./*from  w  ww  .j  av a 2s.c o m*/
 *
 * @param request         HTTP request
 * @param response        HTTP response
 * @param scenarioName    scenario name
 * @param researchGroupId research group to which should be new record assigned
 * @param mimeType        scenario file MIME type
 * @param isPrivate       is scenario private
 * @param description     scenario description
 * @param file            file content
 * @return filled scenario data container
 * @throws RestServiceException error while creating new scenario record
 */
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public ScenarioData create(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("scenarioName") String scenarioName, @RequestParam("researchGroupId") int researchGroupId,
        @RequestParam(value = "mimeType", required = false) String mimeType,
        @RequestParam(value = "private", required = false) boolean isPrivate,
        @RequestParam("description") String description, @RequestParam("file") MultipartFile file)
        throws RestServiceException {
    ScenarioData scenarioData = new ScenarioData();
    scenarioData.setScenarioName(scenarioName);
    scenarioData.setResearchGroupId(researchGroupId);
    scenarioData.setDescription(description);
    scenarioData.setMimeType(mimeType != null ? mimeType : file.getContentType());
    scenarioData.setPrivate(isPrivate);
    scenarioData.setFileName(file.getName());
    scenarioData.setFileLength((int) file.getSize());

    try {
        int pk = scenarioService.create(scenarioData, file);
        scenarioData.setScenarioId(pk);

        Person user = personDao.getLoggedPerson();
        scenarioData.setOwnerName(user.getGivenname() + " " + user.getSurname());
        ResearchGroup group = researchGroupDao.read(scenarioData.getResearchGroupId());
        scenarioData.setResearchGroupName(group.getTitle());

        response.addHeader("Location", buildLocation(request, pk));
        return scenarioData;
    } catch (IOException e) {
        log.error(e);
        throw new RestServiceException(e);
    } catch (SAXException e) {
        log.error(e);
        throw new RestServiceException(e);
    } catch (ParserConfigurationException e) {
        log.error(e);
        throw new RestServiceException(e);
    }
}

From source file:com.tela.pms.PatientController.java

/**
 * createPatient will edit a new patient and update in the cloud db
 *//*w  ww .j  a v a2 s.c o  m*/
@RequestMapping(value = "/editPatient", method = RequestMethod.POST)
public String editPatient(HttpServletRequest request, HttpServletResponse response, Model model,
        @RequestParam("file") MultipartFile file) {

    //Retrieving requests
    String patientId = request.getParameter("id");
    System.out.println(patientId);
    int id = Integer.parseInt(patientId);

    String patientName = request.getParameter("patientName");
    String age = request.getParameter("age");
    String nic = request.getParameter("nic");
    String address = request.getParameter("address");
    String gender = request.getParameter("gender");
    String contactNo = request.getParameter("contactNo");
    String email = request.getParameter("email");
    String tags = request.getParameter("tags");
    String createdAt = request.getParameter("patient_CreatedAt");
    String imagePath = request.getParameter("patient_Photo");
    String existingimagePath = request.getParameter("existingimagePath");
    System.out.println("**** img path " + imagePath);

    if (nic.equals("") || nic == null) {
        nic = "Not Available";
    }
    if (address.equals("") || address == null) {
        address = "Not Available";
    }
    if (contactNo.equals("") || contactNo == null) {
        contactNo = "Not Available";
    }
    if (email.equals("") || email == null) {
        email = "Not@Available";
    }
    if (tags.equals("") || tags == null) {
        tags = "Not Available";
    }

    //Creating a new patient
    Patient patient = new Patient();

    //Retrieving uploaded files
    MultipartFile patientPhoto = file;

    if (patientPhoto.getSize() != 0 && patientPhoto.getOriginalFilename() != null) {
        File cloud_file = null;
        try {
            cloud_file = convertFile(patientPhoto);
        } catch (IOException e1) {
            logger.info("something went wrong in coverting the file @" + new Date());
            e1.printStackTrace();
        }
        String extension = FilenameUtils.getExtension(patientPhoto.getOriginalFilename());
        Long fileSize = patientPhoto.getSize();

        if (extension.equals("JPG") || extension.equals("jpg") || extension.equals("jpeg")
                || extension.equals("JPEG")) {
            try {

                File catalinaBase = new File(System.getProperty("catalina.base")).getAbsoluteFile();
                logger.info("catalinaBase:" + catalinaBase.getAbsolutePath());

                InputStream inputStream = patientPhoto.getInputStream();
                String imageId = "patient-" + Integer.toString(id);
                String fileName = imageId + ".jpg";

                File newFile = new File(catalinaBase,
                        "webapps/pms/WEB-INF/views/images/Uploaded_images/Patients/" + fileName);

                if (!newFile.exists()) {
                    newFile.createNewFile();
                }
                OutputStream outputStream = new FileOutputStream(newFile);
                int read = 0;
                byte[] bytes = new byte[1024];

                while ((read = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, read);
                }
                imagePath = "resources/images/Uploaded_images/Patients/" + fileName;

                logger.info("Patient image successfully uploaded to local repo @" + new Date());
            } catch (FileNotFoundException e) {
                logger.info("something went wrong when patient photo uploading @" + new Date());
                e.printStackTrace();
            } catch (IOException e) {
                logger.info("something went wrong when patient photo uploading @" + new Date());
                e.printStackTrace();
            }

        } else {
            logger.info("Uploaded file is not a jpg or png " + new Date());
            if (gender.equals("Female")) {
                imagePath = "resources/images/patient-female.png";
            } else {
                imagePath = "resources/images/patient-male.png";
            }
        }

    } else {

        if (existingimagePath.contains("patient-male") || existingimagePath.contains("patient-female")) {
            if (gender.equals("Female")) {
                imagePath = "resources/images/patient-female.png";
            } else {
                imagePath = "resources/images/patient-male.png";
            }

        }
    }

    //Updating patient info
    patient.setPatient_Id(id);
    patient.setPatient_Name(patientName);
    patient.setPatient_Age(age);
    patient.setPatient_Address(address);
    patient.setPatient_ContactNo(contactNo);
    patient.setPatient_Gender(gender);
    patient.setPatient_Email(email);
    patient.setPatient_NIC(nic);
    patient.setPatient_Photo(imagePath);
    patient.setPatient_CreatedAt(createdAt);
    patient.setPatient_tags(tags);

    //Calling patient service and updating patient
    patientService.updatePatient(patient);

    //System.out.println(patientName+"  "+age+"   "+patientPhoto.getOriginalFilename()+"   "+nic+"   "+address+"   "+gender+"   "+contactNo+"   "+email);

    String view = "patient";

    Patient editedPatient = patientService.findPatientById(id);
    model.addAttribute("patient", editedPatient);

    List<Prescription> prescriptions = prescriptionService.retrieveAllPrescriptionsByPatientId(id);
    model.addAttribute("prescriptions", prescriptions);

    logger.info("Edited Patient " + id + " retrieved @ " + new Date());
    logger.info("Prescription list " + prescriptions + " retrieved @ " + new Date());
    model.addAttribute("status", "<strong>Successfully </strong> updated the patient! ");
    model.addAttribute("style", "style=\"display:block;margin-top: 5px;\"");
    return view;
}

From source file:fr.xebia.cocktail.CocktailManager.java

/**
 * TODO use PUT instead of POST// ww  w  .  j a va 2s  . c o m
 *
 * @param id    id of the cocktail
 * @param photo to associate with the cocktail
 * @return redirection to display cocktail
 */
@RequestMapping(value = "/cocktail/{id}/photo", method = RequestMethod.POST)
public String updatePhoto(@PathVariable String id, @RequestParam("photo") MultipartFile photo) {

    if (!photo.isEmpty()) {
        try {
            String contentType = fileStorageService.findContentType(photo.getOriginalFilename());
            if (contentType == null) {
                logger.warn("photo",
                        "Skip file with unsupported extension '" + photo.getOriginalFilename() + "'");
            } else {

                InputStream photoInputStream = photo.getInputStream();
                long photoSize = photo.getSize();

                Map metadata = new TreeMap();
                metadata.put("Content-Length", Arrays.asList(new String[] { "" + photoSize }));
                metadata.put("Content-Type", Arrays.asList(new String[] { contentType }));
                metadata.put("Cache-Control", Arrays.asList(
                        new String[] { "public, max-age=" + TimeUnit.SECONDS.convert(365, TimeUnit.DAYS) }));

                /*    ObjectMetadata objectMetadata = new ObjectMetadata();
                    objectMetadata.setContentLength(photoSize);
                    objectMetadata.setContentType(contentType);
                    objectMetadata.setCacheControl("public, max-age=" + TimeUnit.SECONDS.convert(365, TimeUnit.DAYS));*/
                String photoUrl = fileStorageService.storeFile(photo.getBytes(), metadata);

                Cocktail cocktail = cocktailRepository.get(id);
                logger.info("Saved {}", photoUrl);
                cocktail.setPhotoUrl(photoUrl);
                cocktailRepository.update(cocktail);
            }

        } catch (IOException e) {
            throw Throwables.propagate(e);
        }
    }
    return "redirect:/cocktail/" + id;
}

From source file:csns.web.controller.FileManagerController.java

@RequestMapping("/file/replace")
public String replace(@RequestParam Long id, @RequestParam("file") MultipartFile uploadedFile,
        ModelMap models) {//  w  ww . j a v  a2 s  .c om
    File file = fileDao.getFile(id);
    if (!file.isRegular() || file.isDeleted() || file.isFolder())
        return "redirect:/";

    if (!uploadedFile.isEmpty()) {
        User user = SecurityUtils.getUser();
        long diskQuota = user.getDiskQuota() * 1024L * 1024L;
        long diskUsage = fileDao.getDiskUsage(user);
        if (diskUsage - file.getSize() + uploadedFile.getSize() > diskQuota) {
            models.put("message", "error.file.quota.exceeded");
            return "error";
        }

        file.setName(uploadedFile.getOriginalFilename());
        file.setType(uploadedFile.getContentType());
        file.setSize(uploadedFile.getSize());
        file.setDate(new Date());
        file = fileDao.saveFile(file);
        fileIO.save(file, uploadedFile);
    }

    return "redirect:/file/edit?id=" + id;
}

From source file:com.netflix.genie.web.controllers.JobRestController.java

private ResponseEntity<Void> handleSubmitJob(final JobRequest jobRequest, final MultipartFile[] attachments,
        final String clientHost, final String userAgent, final HttpServletRequest httpServletRequest)
        throws GenieException {
    if (jobRequest == null) {
        throw new GeniePreconditionException("No job request entered. Unable to submit.");
    }//from w w  w .j a v a  2  s.  com

    // get client's host from the context
    final String localClientHost;
    if (StringUtils.isNotBlank(clientHost)) {
        localClientHost = clientHost.split(",")[0];
    } else {
        localClientHost = httpServletRequest.getRemoteAddr();
    }

    final JobRequest jobRequestWithId;
    // If the job request does not contain an id create one else use the one provided.
    final String jobId;
    final Optional<String> jobIdOptional = jobRequest.getId();
    if (jobIdOptional.isPresent() && StringUtils.isNotBlank(jobIdOptional.get())) {
        jobId = jobIdOptional.get();
        jobRequestWithId = jobRequest;
    } else {
        jobId = UUID.randomUUID().toString();
        final JobRequest.Builder builder = new JobRequest.Builder(jobRequest.getName(), jobRequest.getUser(),
                jobRequest.getVersion(), jobRequest.getCommandArgs(), jobRequest.getClusterCriterias(),
                jobRequest.getCommandCriteria()).withId(jobId)
                        .withDisableLogArchival(jobRequest.isDisableLogArchival())
                        .withTags(jobRequest.getTags()).withDependencies(jobRequest.getDependencies())
                        .withApplications(jobRequest.getApplications());

        jobRequest.getCpu().ifPresent(builder::withCpu);
        jobRequest.getMemory().ifPresent(builder::withMemory);
        jobRequest.getGroup().ifPresent(builder::withGroup);
        jobRequest.getSetupFile().ifPresent(builder::withSetupFile);
        jobRequest.getDescription().ifPresent(builder::withDescription);
        jobRequest.getEmail().ifPresent(builder::withEmail);
        jobRequest.getTimeout().ifPresent(builder::withTimeout);

        jobRequestWithId = builder.build();
    }

    // Download attachments
    int numAttachments = 0;
    long totalSizeOfAttachments = 0L;
    if (attachments != null) {
        log.info("Saving attachments for job {}", jobId);
        numAttachments = attachments.length;
        for (final MultipartFile attachment : attachments) {
            totalSizeOfAttachments += attachment.getSize();
            log.debug("Attachment name: {} Size: {}", attachment.getOriginalFilename(), attachment.getSize());
            try {
                this.attachmentService.save(jobId, attachment.getOriginalFilename(),
                        attachment.getInputStream());
            } catch (final IOException ioe) {
                throw new GenieServerException(ioe);
            }
        }
    }

    final JobMetadata metadata = new JobMetadata.Builder().withClientHost(localClientHost)
            .withUserAgent(userAgent).withNumAttachments(numAttachments)
            .withTotalSizeOfAttachments(totalSizeOfAttachments).build();

    this.jobCoordinatorService.coordinateJob(jobRequestWithId, metadata);

    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(
            ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(jobId).toUri());

    return new ResponseEntity<>(httpHeaders, HttpStatus.ACCEPTED);
}

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

@RequestMapping(value = "/s/admin/{eventKey}/sponsor", method = RequestMethod.POST)
public String addSponsor(@RequestParam MultipartFile pictureFile, @Valid Sponsor sponsorForm,
        BindingResult result, HttpServletRequest request, RedirectAttributes redirectAttributes,
        @PathVariable("eventKey") String eventKey) {

    if (request.getParameter("cancel") != null) {
        return "redirect:/s/admin/{eventKey}/sponsors";
    }/*from  w w  w  . j ava  2 s. co  m*/

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

    final Event currentEvent = businessService.getEventByEventKey(eventKey);
    sponsorForm.setEvent(currentEvent);

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

        final FileData pictureData = new FileData();

        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) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        sponsorForm.setLogo(pictureData);

    }

    final Sponsor savedSponsor = businessService.saveSponsor(sponsorForm);

    redirectAttributes.addFlashAttribute("successMessage",
            String.format("The sponsor '%s' was added successfully.", savedSponsor.getName()));
    return "redirect:/s/admin/{eventKey}/sponsors";
}

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

@RequestMapping(value = "/s/admin/speaker", method = RequestMethod.POST)
public String addSpeaker(@RequestParam MultipartFile pictureFile, @Valid Speaker speakerForm,
        BindingResult result, HttpServletRequest request, RedirectAttributes redirectAttributes) {

    Event currentEvent = this.businessService.getCurrentEvent();

    redirectAttributes.addAttribute("eventKey", currentEvent.getEventKey());

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

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

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

        final FileData pictureData = new FileData();

        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) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        speakerForm.setPicture(pictureData);

    }

    final Speaker savedSpeaker = businessService.saveSpeaker(speakerForm);

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

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

From source file:gr.abiss.calipso.tiers.controller.AbstractModelWithAttachmentsController.java

@ApiOperation(value = "Add a file uploads to property")
@RequestMapping(value = "{subjectId}/uploads/{propertyName}", method = { RequestMethod.POST,
        RequestMethod.PUT }, consumes = {})
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 {// w w  w.  ja  v  a 2s.  co  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);
    }

    return bf;
}

From source file:org.spirit.spring.handler.BotListAdminHandler.java

public BotListDocFileMetadata uploadCurFile(HttpServletRequest request, Object form, MultipartFile entity)
        throws IllegalStateException, IOException {

    String uploadDir = this.controller.getFileUploadUtil().getUploadDir();
    String filename = entity.getOriginalFilename();
    String uid = BotListUniqueId.getUniqueId();

    String newFilename = "doc" + uid + ".txt";

    File fileUpload = new File(uploadDir + "/" + newFilename);
    entity.transferTo(fileUpload);//from   ww  w.  ja v  a  2  s .  c  o  m

    // Create the file metadata bean
    BotListDocFileMetadata metadata = new BotListDocFileMetadata();

    metadata.setDocFilesize(new Long(entity.getSize()));
    metadata.setDocFilename(newFilename);
    metadata.setDocOriginalname(filename);

    return metadata;

}