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:com.glaf.jbpm.web.springmvc.MxJbpmDeployController.java

@RequestMapping(value = "/deploy", method = RequestMethod.POST)
public ModelAndView deploy(HttpServletRequest request, HttpServletResponse response) {
    String archive = request.getParameter("archive");
    if (LogUtils.isDebug()) {
        logger.debug("deploying archive " + archive);
    }// ww w .  j  av a2  s  .c  om

    MxJbpmProcessDeployer deployer = new MxJbpmProcessDeployer();

    byte[] bytes = null;
    JbpmContext jbpmContext = null;
    try {
        jbpmContext = ProcessContainer.getContainer().createJbpmContext();

        if (jbpmContext != null && jbpmContext.getSession() != null) {
            MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = req.getFileMap();
            Set<Entry<String, MultipartFile>> entrySet = fileMap.entrySet();
            for (Entry<String, MultipartFile> entry : entrySet) {
                MultipartFile mFile = entry.getValue();
                if (mFile.getOriginalFilename() != null && mFile.getSize() > 0) {
                    ProcessDefinition processDefinition = deployer.deploy(jbpmContext, mFile.getBytes());
                    bytes = processDefinition.getFileDefinition().getBytes("processimage.jpg");
                    response.setContentType("image/jpeg");
                    response.setHeader("Pragma", "No-cache");
                    response.setHeader("Expires", "-1");
                    response.setHeader("ICache-Control", "no-cache");
                    response.setDateHeader("Expires", 0L);
                    OutputStream out = response.getOutputStream();
                    out.write(bytes);
                    out.flush();
                    out.close();
                    bytes = null;
                    return null;
                }
            }
        }
    } catch (JbpmException ex) {
        if (jbpmContext != null) {
            jbpmContext.setRollbackOnly();
        }
        request.setAttribute("error_code", 9912);
        request.setAttribute("error_message", "");
        return new ModelAndView("/error");
    } catch (IOException ex) {
        if (jbpmContext != null) {
            jbpmContext.setRollbackOnly();
        }
        request.setAttribute("error_code", 9912);
        request.setAttribute("error_message", "");
        return new ModelAndView("/error");
    } finally {
        Context.close(jbpmContext);
        bytes = null;
    }
    return null;
}

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

/**
 * This method add the image to the profile image storage for the
 * corresponding user./*from ww  w  . j a  v a 2  s.  com*/
 */
@Override
public String saveProfileImage(MultipartFile file, String fileName) throws Exception {
    LOGGER.info("[ProfileImageRequestDAOImpl][saveProfileImage] 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.PROFILE_IMAGE_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][saveProfileImage] end");
    return profileImageBLOBUrl + AzureChatConstants.CONSTANT_EMPTY_STRING;

}

From source file:com.xumpy.thuisadmin.controllers.pages.Finances.java

@RequestMapping(value = "/finances/nieuwBedragDocument/saveDocument", method = RequestMethod.POST)
public String saveBedragDocument(@ModelAttribute("document") NieuwDocument document,
        @RequestParam("file") MultipartFile file) throws IOException {
    DocumentenSrvPojo bedragDocument = new DocumentenSrvPojo();

    bedragDocument.setBedrag(new BedragenSrvPojo(bedragenSrv.findBedrag(document.getBedrag_id())));
    //bedragDocument.setDatum(document.getDatum());
    bedragDocument.setDocument(file.getBytes());
    bedragDocument.setDocument_mime(file.getContentType());
    bedragDocument.setDocument_naam(file.getOriginalFilename());
    bedragDocument.setOmschrijving(document.getOmschrijving());
    bedragDocument.setPk_id(document.getPk_id());

    Log.info("File bytes: " + file.getBytes().length);
    Log.info("Document PK_ID: " + document.getPk_id());

    if (file.getBytes().length == 0 && document.getPk_id() != null) {
        Documenten bedragDocumentOld = documentenSrv.fetchDocument(document.getPk_id());
        bedragDocument.setDocument(bedragDocumentOld.getDocument());
        bedragDocument.setDocument_mime(bedragDocumentOld.getDocument_mime());
        bedragDocument.setDocument_naam(bedragDocumentOld.getDocument_naam());
    }/*from  w  w  w  .j av a  2 s .  co  m*/

    documentenSrv.save(bedragDocument);

    return "redirect:/finances/nieuwBedrag/" + document.getBedrag_id();
}

From source file:io.onedecision.engine.domain.web.DomainController.java

/**
 * Imports JSON representation of contacts.
 * //from   w w w. j a v  a 2s  .co m
 * <p>
 * This is a handy link: http://shancarter.github.io/mr-data-converter/
 * 
 * @param file
 *            A file posted in a multi-part request
 * @return The meta data of the added model
 * @throws IOException
 *             If cannot parse the JSON.
 */
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody DomainModel handleFileUpload(@PathVariable("tenantId") String tenantId,
        @RequestParam(value = "file", required = true) MultipartFile file) throws IOException {
    LOGGER.info(String.format("Uploading domain model for: %1$s", tenantId));
    String content = new String(file.getBytes());

    DomainModel model = objectMapper.readValue(content, new TypeReference<DomainModel>() {
    });
    model.setTenantId(tenantId);

    LOGGER.info(String.format("  found model with %1$d entities", model.getEntities().size()));
    updateModelForTenant(tenantId, model);

    return model;
}

From source file:cs544.wamp_blog_engine.controller.UserController.java

@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String add(@Valid User user, BindingResult result, HttpSession session, RedirectAttributes flashAttr,
        @RequestParam("file") MultipartFile file) {
    String view = "redirect:/";
    System.out.println("userController Add");

    if (!result.hasErrors()) {
        try {/* www  .j a  v a  2 s . c o m*/
            user.setProfilepic(file.getBytes());
        } catch (IOException ex) {
            Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
        }
        userService.addUser(user);
        session.removeAttribute("credential");
        flashAttr.addFlashAttribute("successfulSignup",
                "User signed up succesfully. please  log in to proceed");
        User u = (User) session.getAttribute("loggedUser");
        if (u != null && u.getUserCredential().isAdmin()) {
            view = "redirect:/settings";
        }
    } else {
        for (FieldError err : result.getFieldErrors()) {
            System.out.println("Error:" + err.getField() + ":" + err.getDefaultMessage());
        }
        view = "addUser";
    }
    return view;
}

From source file:mx.com.quadrum.service.impl.TipoContratoServiceImpl.java

@Override
public String editar(TipoContrato tipoContrato, MultipartFile formato) {
    boolean actualizadFormato = false;
    if (!formato.isEmpty()) {
        String path = FORMATOS + "/" + tipoContrato.getId() + ".jasper";
        File jasper = new File(path);
        if (jasper.exists()) {
            try {
                jasper.delete();/*from   w w w  .  j  a  v  a2s .  c o m*/
                crearArchivoContenido(path, formato.getBytes());
                actualizadFormato = true;
            } catch (IOException ex) {
                Logger.getLogger(TipoContratoServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    if (tipoContratoRepository.editar(tipoContrato)) {
        if (!actualizadFormato) {
            return UPDATE_CORRECT + TIPO_CONTRATO
                    + " pero la plantilla no pudo ser modificada, compruebe que no esta siendo usada en otra pestaa o navegador.";
        }
        return UPDATE_CORRECT + TIPO_CONTRATO;
    }
    return ERROR_HIBERNATE;
}

From source file:com.epam.ta.reportportal.core.user.impl.EditUserHandler.java

private void validatePhoto(MultipartFile file) throws IOException {
    expect(file.getSize() < MAX_PHOTO_SIZE, equalTo(true)).verify(BINARY_DATA_CANNOT_BE_SAVED,
            "Image size should be less than 1 mb");
    MediaType mediaType = new AutoDetectParser().getDetector().detect(TikaInputStream.get(file.getBytes()),
            new Metadata());
    String subtype = mediaType.getSubtype();
    expect(ImageFormat.fromValue(subtype), notNull()).verify(BINARY_DATA_CANNOT_BE_SAVED,
            "Image format should be " + ImageFormat.getValues());
    BufferedImage read = ImageIO.read(file.getInputStream());
    expect((read.getHeight() <= MAX_PHOTO_HEIGHT) && (read.getWidth() <= MAX_PHOTO_WIDTH), equalTo(true))
            .verify(BINARY_DATA_CANNOT_BE_SAVED, "Image size should be 300x500px or less");
}

From source file:com.appspot.potlachkk.controller.ImageSvc.java

@Multipart
@RequestMapping(value = ImageSvcApi.IMG_SVC_PATH, method = RequestMethod.POST)
public @ResponseBody Long addImage(@RequestParam("imageData") MultipartFile imageFile) throws Exception {

    //TODO here could be some kind of validation to
    // see what kind of data is really uploaded to the 
    // server/* w  w  w. ja  va  2s.  c o  m*/
    GiftImage img = new GiftImage();

    img.setMimeType(imageFile.getContentType());
    img.setFilename(imageFile.getOriginalFilename());

    Blob data = new Blob(imageFile.getBytes());

    img.setData(data);

    GiftImage retImg = images.save(img);
    return retImg.getId();
}

From source file:com.turn.griffin.GriffinService.java

@RequestMapping(value = { "/localrepo", "/globalrepo" }, method = { RequestMethod.POST, RequestMethod.PUT })
public @ResponseBody String pushToRepo(@RequestParam(value = "blobname", required = true) String blobname,
        @RequestParam(value = "dest", required = true) String dest,
        @RequestParam(value = "file", required = true) MultipartFile file) {

    if (!StringUtils.isNotBlank(blobname)) {
        return "Blobname cannot be empty\n";
    }/*from ww w .  j a va2  s .c  o  m*/

    if (!StringUtils.isNotBlank(dest)) {
        return "Dest cannot be empty\n";
    }

    try {
        File tempFile = File.createTempFile("gfn", null, null);
        byte[] bytes = file.getBytes();
        BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(tempFile));
        stream.write(bytes);
        stream.close();
        module.get().syncBlob(blobname, dest, tempFile.getAbsolutePath());
        return String.format("Pushed file as blob %s to destination %s%n", blobname, dest);
    } catch (Exception e) {
        logger.error(String.format("POST request failed%n%s%n", ExceptionUtils.getStackTrace(e)));
        return String.format("Unable to push file as blob %s to destination %s%n", blobname, dest);
    } // TODO: Delete tempFile
}