Example usage for org.springframework.web.multipart MultipartFile getBytes

List of usage examples for org.springframework.web.multipart MultipartFile getBytes

Introduction

In this page you can find the example usage for org.springframework.web.multipart MultipartFile getBytes.

Prototype

byte[] getBytes() throws IOException;

Source Link

Document

Return the contents of the file as an array of bytes.

Usage

From source file:serviceComposite.UserServiceComposite.java

@Override
public void updateProfilePicture(UserEntity user, MultipartFile file) {
    FileEntity oldProfilePicture = this.fileService.findProfilePicture(user);
    if (oldProfilePicture != null) {
        this.fileService.remove(oldProfilePicture);
        user = this.userDao.findById(user.getId());
    }//from  ww w  .  j a v  a2s .  com
    try {
        this.fileService.add(file.getOriginalFilename(), file.getContentType(), file.getBytes(), user, true);
    } catch (IOException e) {
    }
}

From source file:org.jhk.pulsing.web.controller.UserController.java

@RequestMapping(value = "/createUser", method = RequestMethod.POST, consumes = {
        MediaType.MULTIPART_FORM_DATA_VALUE })
public @ResponseBody Result<User> createUser(@RequestParam User user,
        @RequestParam(name = "picture", required = false) MultipartFile mPicture) {
    _LOGGER.debug("UserController.createUser: " + user + "; "
            + (mPicture != null ? ("picture size is: " + mPicture.getSize()) : "picture not submitted"));

    if (mPicture != null) {
        try {/*  w ww  .  j  a v a  2 s  . c  o  m*/
            ByteBuffer pBuffer = ByteBuffer.wrap(mPicture.getBytes());

            Picture picture = Picture.newBuilder().build();
            picture.setContent(pBuffer);
            picture.setName(mPicture.getOriginalFilename());
            user.setPicture(picture);
        } catch (IOException iException) {
            _LOGGER.error("Could not get picture bytes", iException);
        }
    }

    return userService.createUser(user);
}

From source file:org.openbaton.nfvo.api.RestVNFPackage.java

/**
 * Adds a new VNFPackage to the VNFPackages repository
 *///from w  ww .  j  av  a 2s. c  o  m
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public String onboard(@RequestParam("file") MultipartFile file,
        @RequestHeader(value = "project-id") String projectId)
        throws IOException, VimException, NotFoundException, SQLException, PluginException {

    log.debug("Onboarding");
    if (!file.isEmpty()) {
        byte[] bytes = file.getBytes();
        VirtualNetworkFunctionDescriptor virtualNetworkFunctionDescriptor = vnfPackageManagement.onboard(bytes,
                projectId);
        return "{ \"id\": \"" + virtualNetworkFunctionDescriptor.getVnfPackageLocation() + "\"}";
    } else
        throw new IOException("File is empty!");
}

From source file:com.jaspersoft.jasperserver.war.themes.action.ThemeAction.java

public Event reuploadTheme(RequestContext context) throws Exception {
    String themeName = context.getRequestParameters().get("themeName");
    String folderUri = context.getRequestParameters().get(FOLDER_URI);

    try {//from w ww  .  ja v  a2 s.c  o m
        ExecutionContext executionContext = JasperServerUtil.getExecutionContext(context);

        byte[] fileContent;
        MultipartFile multipartFile = context.getRequestParameters().getMultipartFile("themeZip");

        if (multipartFile != null) {
            fileContent = multipartFile.getBytes();
        } else {
            fileContent = (byte[]) context.getFlowScope().get(FILE_CONTENT);
            context.getFlowScope().remove(FILE_CONTENT);
        }
        themeService.addZippedTheme(executionContext, folderUri, themeName, fileContent, true);

        String themeUri = folderUri + "/" + themeName;
        boolean isActiveTheme = themeService.isActiveThemeFolder(executionContext, themeUri);

        JSONObject jsonObject = new JSONObject().put("isActiveTheme", isActiveTheme);
        jsonObject.put("themeUri", themeUri);

        JSONObject ret = new JSONConverterBase().createJSONResponse(jsonObject);
        context.getRequestScope().put(AJAX_RESPONSE_MODEL, ret.toString());

        return success();
    } catch (Exception ex) {
        log.error("cannot reupload theme", ex);
        String errorMsg = messages.getMessage(THEMES_CANNOT_UPLOAD, new Object[] { ex.getMessage() },
                LocaleContextHolder.getLocale());
        JSONObject ret = new JSONConverterBase().createErrorJSONResponse(errorMsg);
        context.getRequestScope().put(AJAX_RESPONSE_MODEL, ret.toString());

        return error();
    }
}

From source file:com.casker.portfolio.service.PortfolioServiceImpl.java

/**
 * @param portfolio/*from   www. j  a  v a2 s  . co  m*/
 */
private void saveImageFile(String fileName, MultipartFile multipartFile) {
    File file = new File(filePath + File.separator + fileName);

    if (multipartFile == null || file.isDirectory()) {
        return;
    }

    try {
        FileUtils.writeByteArrayToFile(file, multipartFile.getBytes());
    } catch (IOException e) {
        throw new RuntimeException("Unable to save image", e);
    }
}

From source file:com.microsoftopentechnologies.azchat.web.dao.ProfileImageRequestDAOImpl.java

/**
 * This method adds the image to the azure storage.
 *//*from  www. j  av  a2  s. com*/
@Override
public String savePhoto(MultipartFile file, String fileName) throws Exception {
    LOGGER.info("[ProfileImageRequestDAOImpl][savePhoto] start");
    LOGGER.debug("File Name : " + fileName);
    InputStream inputStream = null;
    URI profileImageBLOBUrl = null;
    byte[] byteArr = null;
    byteArr = file.getBytes();
    inputStream = new ByteArrayInputStream(byteArr);
    CloudBlobContainer cloudBlobContainer = AzureChatStorageUtils
            .getCloudBlobContainer(AzureChatConstants.PHOTO_UPLOAD_CONTAINER);
    AzureChatStorageUtils.generateSASURL(cloudBlobContainer);
    CloudBlockBlob blob = cloudBlobContainer.getBlockBlobReference(fileName);
    blob.getProperties().setContentType(file.getContentType());
    blob.upload(inputStream, byteArr.length);
    profileImageBLOBUrl = blob.getUri();
    LOGGER.debug("Profile Blob URL: " + profileImageBLOBUrl);
    LOGGER.info("[ProfileImageRequestDAOImpl][savePhoto] end");
    return profileImageBLOBUrl + AzureChatConstants.CONSTANT_EMPTY_STRING;
}

From source file:dijalmasilva.controllers.ControladorUser.java

@RequestMapping(value = { "/new" }, method = RequestMethod.POST)
public String newUser(UsuarioForm u, HttpServletRequest req, Date dataDeNascimento, MultipartFile foto)
        throws IOException {
    Usuario usuario = this.convertToUsuario(u, dataDeNascimento.toLocalDate());
    usuario.setConta("ATIVADA");
    if (foto.getSize() != 0) {
        usuario.setFoto(foto.getBytes());
    }//from  www. j  a v  a 2 s  . c  o m
    Usuario user = serviceUser.salvarUsuario(usuario);
    if (user == null) {
        req.setAttribute("result", "No foi possvel criar a conta, verifique se todos os campos foram"
                + " preenchidos corretamente!");
    } else {
        req.setAttribute("result", "Usurio cadastrado com sucesso." + "\n Faa login e aproveite!");
    }

    return "/index";
}

From source file:io.github.microcks.web.ImportController.java

@RequestMapping(value = "/import", method = RequestMethod.POST)
public ResponseEntity<?> importRepository(@RequestParam(value = "file") MultipartFile file) {
    log.debug("Importing new services and resources definitions");
    if (!file.isEmpty()) {
        log.debug("Content type of " + file.getOriginalFilename() + " is " + file.getContentType());
        if (MediaType.APPLICATION_JSON_VALUE.equals(file.getContentType())) {
            try {
                byte[] bytes = file.getBytes();
                String json = new String(bytes);
                importExportService.importRepository(json);
            } catch (Exception e) {
                log.error(e.getMessage());
            }/*from w  ww.j  av  a2s .co  m*/
        }
    }
    return new ResponseEntity<Object>(HttpStatus.CREATED);
}

From source file:cs425.yogastudio.controller.ProductController.java

@RequestMapping(value = "/addProduct", method = RequestMethod.POST)
public String addProduct(String productName, String price, String description, Model model, HttpSession session,
        @RequestParam("file") MultipartFile file) {

    double thePrice = Double.parseDouble(price);
    Product newProduct = new Product(productName, thePrice, description);

    if (!file.isEmpty()) {
        try {//from  w ww . ja va 2s  . c o m
            newProduct.setProductImage(file.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    productService.addProduct(newProduct);
    model.addAttribute("added", newProduct.getProductName());
    session.setAttribute("added", newProduct.getProductName());
    return "redirect:/addProductSuccess";
}

From source file:com.microsoftopentechnologies.azchat.web.dao.ProfileImageRequestDAOImpl.java

/**
 * This method save/add the video to the temporary azure storage.
 *//*w  ww . ja v  a2s.  c  om*/
@Override
public String saveTempVideo(MultipartFile file, String fileName) throws Exception {
    LOGGER.info("[ProfileImageRequestDAOImpl][saveTempVideo] start");
    LOGGER.debug("File Name : " + fileName);
    InputStream inputStream = null;
    URI profileImageBLOBUrl = null;
    byte[] byteArr = null;
    byteArr = file.getBytes();
    inputStream = new ByteArrayInputStream(byteArr);

    CloudBlobContainer cloudBlobContainer = AzureChatStorageUtils
            .getCloudBlobContainer(AzureChatConstants.TEMP_UPLOAD_CONTAINER);
    AzureChatStorageUtils.generateSASURL(cloudBlobContainer);
    CloudBlockBlob blob = cloudBlobContainer.getBlockBlobReference(fileName);
    blob.getProperties().setContentType(file.getContentType());
    blob.upload(inputStream, byteArr.length);
    profileImageBLOBUrl = blob.getUri();
    LOGGER.debug("Profile Blob URL: " + profileImageBLOBUrl);
    LOGGER.info("[ProfileImageRequestDAOImpl][saveTempVideo] end");
    return profileImageBLOBUrl + AzureChatConstants.CONSTANT_EMPTY_STRING;
}