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:net.duckling.ddl.web.sync.FileContentController.java

private void doSingleUpload(HttpServletRequest request, HttpServletResponse response, MultipartFile file,
        PathName pathName, String mode, int fver) {
    Context ctx = ContextUtil.retrieveContext(request);
    String device = ctx.getDevice();
    String uid = ctx.getUid();//  w w w  .ja  v a 2 s  .  c om
    int tid = ctx.getTid();
    long size = file.getSize();

    // ?
    Resource parentResource = folderPathService.getResourceByPath(tid, pathName.getContextPath());
    if (parentResource == null) {
        JsonResponse.notFound(response);
        return;
    }

    if (pathName.getName().endsWith(".ddoc")) {
        String title = pathName.getName().substring(0, pathName.getName().length() - ".ddoc".length());
        List<Resource> resources = resourceService.getResourceByTitle(tid, parentResource.getRid(),
                LynxConstants.TYPE_PAGE, title);
        Resource resource = CollectionUtils.isEmpty(resources) ? null : resources.get(0);
        if (resource != null) {
            JsonResponse.sameFileExisted(response);
            return;
        }
        int rid = resourceOperateService.createNewPage(parentResource.getRid(), title, tid, uid);
        FileMeta meta = fileMetaService.get(tid, Long.valueOf(rid));
        meta.setUploadDevice(device);
        JsonResponse.fileMeta(response, meta);
        return;
    }

    List<Resource> resources = resourceService.getResourceByTitle(tid, parentResource.getRid(),
            LynxConstants.TYPE_FILE, pathName.getName());
    Resource resource = CollectionUtils.isEmpty(resources) ? null : resources.get(0);
    if (mode.equals("add")) {
        if (resource != null) {
            FileMeta meta = fileMetaService.get(tid, Long.valueOf(resource.getRid()));
            JsonResponse.fileVersionConflict(response, meta);
            return;
        }
    } else if (mode.equals("update")) {
        if (resource != null) {
            int existedFileVersion = resource.getLastVersion();
            if (fver != existedFileVersion) {
                FileMeta meta = fileMetaService.get(tid, Long.valueOf(resource.getRid()));
                JsonResponse.fileVersionConflict(response, meta);
                return;
            }
        }
    } else if (mode.equals("overwrite")) {
        // Do nothing.
    }

    FileVersion fv = null;
    try {
        fv = resourceOperateService.upload(uid, tid, parentResource.getRid(), pathName.getName(), size,
                file.getInputStream(), true, true, false, null, device);
    } catch (IOException e) {
        JsonResponse.error(response);
        LOG.error(e.getMessage());
        return;
    } catch (NoEnoughSpaceException e) {
        JsonResponse.error(response);
    } finally {
        try {
            file.getInputStream().close();
        } catch (IOException ignored) {
        }
    }

    if (fv != null) {
        // ??
        FileMeta meta = fileMetaService.get(tid, Long.valueOf(fv.getRid()));
        meta.setUploadDevice(device);
        JsonResponse.fileMeta(response, meta);
    } else {
        JsonResponse.error(response);
    }

}

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

@RequestMapping("/file/upload")
public String upload(@RequestParam(required = false) Long parentId,
        @RequestParam("file") MultipartFile uploadedFile, ModelMap models) {
    File parent = null;/* ww w .  j  a v  a 2 s.c  o m*/
    String redirectUrl = "redirect:/file/";
    if (parentId != null) {
        parent = fileDao.getFile(parentId);
        redirectUrl += "view?id=" + parentId;
    }

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

        File file = new File();
        file.setName(uploadedFile.getOriginalFilename());
        file.setType(uploadedFile.getContentType());
        file.setSize(uploadedFile.getSize());
        file.setOwner(user);
        file.setRegular(true);
        if (parent != null) {
            file.setParent(parent);
            file.setPublic(parent.isPublic());
        }
        file = fileDao.saveFile(file);

        fileIO.save(file, uploadedFile);
    }

    return redirectUrl;
}

From source file:org.opencron.server.controller.TerminalController.java

@RequestMapping("/upload")
public void upload(HttpSession httpSession, HttpServletResponse response, String token,
        @RequestParam(value = "file", required = false) MultipartFile[] file, String path) {
    TerminalClient terminalClient = TerminalSession.get(token);
    boolean success = true;
    if (terminalClient != null) {
        for (MultipartFile ifile : file) {
            String tmpPath = httpSession.getServletContext().getRealPath("/") + "upload" + File.separator;
            File tempFile = new File(tmpPath, ifile.getOriginalFilename());
            try {
                ifile.transferTo(tempFile);
                if (CommonUtils.isEmpty(path)) {
                    path = ".";
                } else if (path.endsWith("/")) {
                    path = path.substring(0, path.lastIndexOf("/"));
                }/*from   w  w  w.  j  av a2 s.  co  m*/
                terminalClient.upload(tempFile.getAbsolutePath(), path + "/" + ifile.getOriginalFilename(),
                        ifile.getSize());
                tempFile.delete();
            } catch (Exception e) {
                success = false;
            }
        }
    }
    WebUtils.writeJson(response, success ? "true" : "false");
}

From source file:com.courtalon.gigaMvcGalerie.web.ImageController.java

@RequestMapping(value = "/images/data", method = RequestMethod.POST, produces = "application/json")
@ResponseBody//from   w  ww. ja  v a 2  s .c  om
@JsonView(AssetOnly.class)
public Image upload(@RequestParam("file") MultipartFile file,
        @RequestParam("licenseId") Optional<Integer> licenseId,
        @RequestParam("sourceId") Optional<Integer> sourceId,
        @RequestParam("tagsId") Optional<List<Integer>> tagsId) {
    Image img = null;
    try {
        img = getImageRepository()
                .save(new Image(0, file.getOriginalFilename(), "", new Date(), file.getOriginalFilename(),
                        file.getContentType(), file.getSize(), DigestUtils.md5Hex(file.getInputStream())));

        getImageRepository().saveImageFile(img.getId(), file.getInputStream());
        img.addTag(getTagRepository().findByLibelleAndSystemTag(TagRepository.UPLOADED, true));
        img.setLicense(getLicenseTypeRepository().findOne(licenseId.orElse(LicenseType.NO_LICENSE_ID)));
        img.setSource(getAssetSourceRepository().findOne(sourceId.orElse(AssetSource.UNKOWN_SOURCE_ID)));
        final Image image = img;
        if (tagsId.isPresent()) {
            tagsId.get().forEach(id -> image.addTag(getTagRepository().findByIdAndSystemTag(id, false)));
        }
        getImageRepository().save(img);

    } catch (IOException e) {
        log.error(e);
        throw new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, "could not save uploaded image");
    }
    return img;
}

From source file:com.vmware.appfactory.recipe.controller.RecipeApiController.java

@ResponseBody
@RequestMapping(value = "/recipes/uploadfile", method = RequestMethod.POST)
public RecipeFileUploadResponse uploadRecipeFile(@RequestParam(value = "recipeFile") MultipartFile recipeFile)
        throws AfBadRequestException, AfServerErrorException {
    _log.debug("Uploading recipe file");
    _log.debug("  Original Name = " + recipeFile.getOriginalFilename());
    _log.debug("  File Size     = " + recipeFile.getSize());

    try {/*w w  w .  j a v  a2 s . c  o m*/
        DsDatastore ds = null;
        Long dsId = Long.valueOf(_config.getLong(ConfigRegistryConstants.DATASTORE_DEFAULT_RECIPE_ID));
        _log.debug("  DS ID = " + dsId);

        if (dsId == null) {
            throw new AfBadRequestException("No datastore selected for recipe uploads");
        }

        ds = _dsClient.findDatastore(dsId, true);
        if (ds == null) {
            throw new AfBadRequestException("Invalid datastore ID " + dsId + " for recipe uploads");
        }

        /* Create a unique folder using timestamp */
        String dest = ds.createDirsIfNotExists("recipe-files", "" + AfCalendar.Now());
        _log.debug("  Created folder " + dest);

        dest = ds.buildPath(dest, recipeFile.getOriginalFilename());
        _log.debug("  Copying to " + dest);

        ds.copy(recipeFile, dest, null);
        URI uri = DsUtil.generateDatastoreURI(dsId, dest);
        _log.debug("  Copy complete: URI = " + uri.toString());

        RecipeFileUploadResponse response = new RecipeFileUploadResponse();
        response.uri = uri;
        return response;
    } catch (DsException ex) {
        throw new AfServerErrorException(ex);
    } catch (IOException ex) {
        throw new AfServerErrorException(ex);
    } catch (URISyntaxException ex) {
        throw new AfServerErrorException(ex);
    }
}

From source file:edu.wisc.doit.tcrypt.controller.EncryptController.java

@RequestMapping(value = "/encryptFile", method = RequestMethod.POST)
public ModelAndView encryptFile(@RequestParam("fileToEncrypt") MultipartFile file,
        @RequestParam("selectedServiceName") String serviceName, HttpServletResponse response)
        throws Exception {
    if (file.isEmpty()) {
        ModelAndView modelAndView = encryptTextInit();
        modelAndView.addObject("selectedServiceName", serviceName);
        return modelAndView;
    }/*from  w w  w. j a va2s .c  o  m*/

    final FileEncrypter fileEncrypter = this.getFileEncrypter(serviceName);
    final String filename = FilenameUtils.getName(file.getOriginalFilename());

    response.setHeader("Content-Type", "application/x-tar");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + ".tar" + "\"");

    final long size = file.getSize();
    try (final InputStream inputStream = file.getInputStream();
            final ServletOutputStream outputStream = response.getOutputStream()) {

        fileEncrypter.encrypt(filename, (int) size, inputStream, outputStream);
    }

    return null;
}

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

@RequestMapping(value = "/actualiza", method = RequestMethod.POST)
public String actualiza(HttpServletRequest request, @Valid Producto producto, BindingResult bindingResult,
        Errors errors, Model modelo, RedirectAttributes redirectAttributes,
        @RequestParam(value = "imagen", required = false) MultipartFile archivo) {
    if (bindingResult.hasErrors()) {
        log.error("Hubo algun error en la forma, regresando");
        return "inventario/producto/edita";
    }/*from  w w w  .j  a v  a2  s.  co m*/

    try {
        if (archivo != null && !archivo.isEmpty()) {
            log.debug("SUBIENDO ARCHIVO: {}", archivo.getOriginalFilename());
            Imagen imagen = new Imagen(archivo.getOriginalFilename(), archivo.getContentType(),
                    archivo.getSize(), archivo.getBytes());
            producto.getImagenes().add(imagen);
        }
        Usuario usuario = ambiente.obtieneUsuario();
        producto = productoDao.actualiza(producto, usuario);
    } catch (IOException e) {
        log.error("No se pudo actualizar 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/edita";
    } catch (ConstraintViolationException e) {
        log.error("No se pudo actualizar 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/edita";
    }

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

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

From source file:de.hska.ld.content.service.impl.DocumentServiceImpl.java

@Override
public Long addAttachment(Long documentId, MultipartFile file, String fileName) {
    try {//from   w w w  .  j  av  a 2 s  .c  o m
        return addAttachment(documentId, file.getInputStream(), fileName, file.getSize());
    } catch (IOException e) {
        throw new ValidationException("file");
    }
}

From source file:com.devnexus.ting.web.controller.CallForPapersController.java

@RequestMapping(value = "/cfp", method = RequestMethod.POST)
public String addCfp(@Valid @ModelAttribute("cfpSubmission") CfpSubmissionForm cfpSubmission,
        BindingResult bindingResult, ModelMap model, HttpServletRequest request,
        RedirectAttributes redirectAttributes) {

    if (request.getParameter("cancel") != null) {
        return "redirect:/s/index";
    }// w  w w .  j a  va 2 s.  co m
    if (request.getParameter("addSpeaker") != null) {
        prepareReferenceData(model, request.isSecure());
        CfpSubmissionSpeaker speaker = new CfpSubmissionSpeaker();
        speaker.setCfpSubmission(cfpSubmission);
        cfpSubmission.getSpeakers().add(speaker);
        return "/cfp";
    }

    if (request.getParameter("removeSpeaker") != null) {
        prepareReferenceData(model, request.isSecure());
        cfpSubmission.getSpeakers().remove(Integer.valueOf(request.getParameter("removeSpeaker")).intValue());
        return "/cfp";
    }

    final String reCaptchaEnabled = environment.getProperty("recaptcha.enabled");
    final String recaptchaPrivateKey = environment.getProperty("recaptcha.privateKey");

    if (Boolean.valueOf(reCaptchaEnabled)) {
        String remoteAddr = request.getRemoteAddr();
        ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
        reCaptcha.setPrivateKey(recaptchaPrivateKey);

        String challenge = request.getParameter("recaptcha_challenge_field");
        String uresponse = request.getParameter("recaptcha_response_field");
        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);

        if (!reCaptchaResponse.isValid()) {
            ObjectError error = new ObjectError("error", "Please insert the correct CAPTCHA.");
            bindingResult.addError(error);
            prepareReferenceData(model, request.isSecure());
            return "/cfp";
        }
    }

    if (bindingResult.hasErrors()) {
        prepareReferenceData(model, request.isSecure());
        return "/cfp";
    }

    final Event eventFromDb = businessService.getCurrentEvent();
    final CfpSubmission cfpSubmissionToSave = new CfpSubmission();

    if (cfpSubmission.getSpeakers().size() < 1) {
        ObjectError error = new ObjectError("error", "Please submit at least 1 speaker.");
        bindingResult.addError(error);
        prepareReferenceData(model, request.isSecure());
        return "/cfp";
    }

    if (cfpSubmission.getPictureFiles().size() != cfpSubmission.getSpeakers().size()) {
        ObjectError error = new ObjectError("error", "Please submit a picture for each speaker.");
        bindingResult.addError(error);
        prepareReferenceData(model, request.isSecure());
        return "/cfp";
    }

    cfpSubmissionToSave.setDescription(cfpSubmission.getDescription());
    cfpSubmissionToSave.setEvent(eventFromDb);

    cfpSubmissionToSave.setPresentationType(cfpSubmission.getPresentationType());
    cfpSubmissionToSave.setSessionRecordingApproved(cfpSubmission.isSessionRecordingApproved());
    cfpSubmissionToSave.setSkillLevel(cfpSubmission.getSkillLevel());
    cfpSubmissionToSave.setSlotPreference(cfpSubmission.getSlotPreference());
    cfpSubmissionToSave.setTitle(cfpSubmission.getTitle());
    cfpSubmissionToSave.setTopic(cfpSubmission.getTopic());

    int index = 0;
    for (CfpSubmissionSpeaker cfpSubmissionSpeaker : cfpSubmission.getSpeakers()) {

        final MultipartFile picture = cfpSubmission.getPictureFiles().get(index);
        InputStream pictureInputStream = null;

        try {
            pictureInputStream = picture.getInputStream();
        } catch (IOException e) {
            LOGGER.error("Error processing Image.", e);
            bindingResult.addError(new FieldError("cfpSubmission", "pictureFile", "Error processing Image."));
            prepareReferenceData(model, request.isSecure());
            return "/cfp";
        }

        if (pictureInputStream != null && picture.getSize() > 0) {
            SystemInformationUtils
                    .setSpeakerImage(
                            "CFP_" + cfpSubmissionSpeaker.getFirstName() + "_"
                                    + cfpSubmissionSpeaker.getLastName() + "_" + picture.getOriginalFilename(),
                            pictureInputStream);
        }

        index++;

        final CfpSubmissionSpeaker cfpSubmissionSpeakerToSave = new CfpSubmissionSpeaker();

        cfpSubmissionSpeakerToSave.setEmail(cfpSubmissionSpeaker.getEmail());
        cfpSubmissionSpeakerToSave.setBio(cfpSubmissionSpeaker.getBio());
        cfpSubmissionSpeakerToSave.setFirstName(cfpSubmissionSpeaker.getFirstName());
        cfpSubmissionSpeakerToSave.setGithubId(cfpSubmissionSpeaker.getGithubId());
        cfpSubmissionSpeakerToSave.setGooglePlusId(cfpSubmissionSpeaker.getGooglePlusId());
        cfpSubmissionSpeakerToSave.setLanyrdId(cfpSubmissionSpeaker.getLanyrdId());
        cfpSubmissionSpeakerToSave.setLastName(cfpSubmissionSpeaker.getLastName());
        cfpSubmissionSpeakerToSave.setLinkedInId(cfpSubmissionSpeaker.getLinkedInId());
        cfpSubmissionSpeakerToSave.setTwitterId(cfpSubmissionSpeaker.getTwitterId());
        cfpSubmissionSpeakerToSave.setLocation(cfpSubmissionSpeaker.getLocation());
        cfpSubmissionSpeakerToSave.setMustReimburseTravelCost(cfpSubmissionSpeaker.isMustReimburseTravelCost());
        cfpSubmissionSpeakerToSave.setTshirtSize(cfpSubmissionSpeaker.getTshirtSize());
        cfpSubmissionSpeakerToSave.setPhone(cfpSubmissionSpeaker.getPhone());
        cfpSubmissionSpeakerToSave.setCfpSubmission(cfpSubmissionToSave);
        cfpSubmissionToSave.getSpeakers().add(cfpSubmissionSpeakerToSave);

    }

    LOGGER.info(cfpSubmissionToSave.toString());
    businessService.saveAndNotifyCfpSubmission(cfpSubmissionToSave);

    return "redirect:/s/add-cfp-success";
}

From source file:org.apigw.authserver.web.controller.ApplicationManagementController.java

private Certificate createCertificate(MultipartFile certificate, BindingResult result) {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    Certificate cert = new Certificate();
    if (certificate != null && certificate.getSize() > 0) {

        try {/*from  ww w.  j  a v  a 2  s .  c  om*/
            PEMReader r = new PEMReader(
                    new InputStreamReader(new ByteArrayInputStream(certificate.getBytes())));
            Object certObj = r.readObject();

            long reference = System.currentTimeMillis();

            // validate certificate
            if (certObj instanceof X509Certificate) {
                X509Certificate x509cert = (X509Certificate) certObj;
                BigInteger serialNumber = x509cert.getSerialNumber();

                String issuerDn = x509cert.getIssuerDN().getName();
                String subjectDn = x509cert.getSubjectDN().getName();

                cert.setCertificate(certificate.getBytes());
                cert.setSerialNumber(serialNumber.toString());
                cert.setIssuer(issuerDn);
                cert.setSubject(subjectDn);
                cert.setSubjectCommonName(extractFromDn(subjectDn, "CN"));
                cert.setSubjectOrganization(extractFromDn(subjectDn, "O"));
                cert.setSubjectOrganizationUnit(extractFromDn(subjectDn, "OU"));
                cert.setSubjectLocation(extractFromDn(subjectDn, "L"));
                cert.setSubjectCountry(extractFromDn(subjectDn, "C"));
                cert.setNotAfter(x509cert.getNotAfter());
                cert.setNotBefore(x509cert.getNotBefore());
            } else {
                String line;
                StringBuilder certString = new StringBuilder();
                while ((line = r.readLine()) != null) {
                    certString.append(line + "\n");
                }
                log.warn(
                        "Bad certificate [{}]: Provided certificate was of the wrong type: {}. Certificate: \n{}",
                        new Object[] { reference, certObj, certString.toString() });
                result.rejectValue("certificates", "invalid.certificate",
                        "Certifikatet r ej giltigt (Reference: " + reference + ")");
            }

            r.close();
        } catch (IOException e) {
            log.warn("Bad certificate");
            result.rejectValue("certificates", "invalid.certificate", "Certifikatet r ej giltigt ");
        }
    }
    return cert;
}