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.timesheet.controller.TimeSheetController.java

@RequestMapping(value = "/registercompany", method = RequestMethod.POST)
public ModelAndView registerComapny(@ModelAttribute("company") Company company,
        @RequestParam("file") MultipartFile file) {
    ModelAndView mav = new ModelAndView("redirect:/company-reg");

    try {/* w w  w  .j av  a 2  s . c om*/

        Blob blob = new javax.sql.rowset.serial.SerialBlob(file.getBytes());

        company.setLogo(blob);

        Integer compnayId = companyService.addCompany(company);

        System.out.println("@@@@@@@@@@@@@@@ Company ID:" + compnayId);
        String password = utils.pwdGenerator();

        User user = new User();
        user.setCompany(company);
        user.setDepartment("Admin");
        user.setName(company.getName());
        user.setEmail(company.getEmail());
        user.setRole("admin");
        user.setPassword(password);
        user.setUserIdentifier("admin");

        userService.addUser(user);

        //Send confirmation email
        String to = company.getEmail();
        String subject = "Time sheet registration for your company ";
        String body = "Thank you for registration , Your login information : Email " + company.getEmail()
                + "\n Password : " + password;

        emailService.sendMail(to, subject, body);

    } catch (SQLException ex) {
        Logger.getLogger(TimeSheetController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(TimeSheetController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (MessagingException ex) {
        Logger.getLogger(TimeSheetController.class.getName()).log(Level.SEVERE, null, ex);
    }

    return mav;
}

From source file:wad.controller.ReceiptController.java

@RequestMapping(method = RequestMethod.POST)
public String addReceipt(@RequestParam("file") MultipartFile file, @PathVariable Long expenseId,
        @ModelAttribute Receipt receipt, BindingResult bindingResult, @ModelAttribute Expense expense,
        SessionStatus status, RedirectAttributes redirectAttrs) throws IOException {

    if (expense == null || !expense.isEditableBy(userService.getCurrentUser())) {
        throw new ResourceNotFoundException();
    }/*  ww  w  . j  a v  a2 s.c om*/

    receipt.setName(file.getName());
    receipt.setMediaType(file.getContentType());
    receipt.setSize(file.getSize());
    receipt.setContent(file.getBytes());
    receipt.setSubmitted(new Date());
    receipt.setExpense(expense);

    receiptValidator.validate(receipt, bindingResult);

    if (bindingResult.hasErrors()) {
        redirectAttrs.addFlashAttribute("errors", bindingResult.getAllErrors());
        return "redirect:/expenses/" + expense.getId();
    }

    receiptRepository.save(receipt);

    status.setComplete();

    return "redirect:/expenses/" + expense.getId();
}

From source file:com.jlfex.hermes.main.AccountPersonalController.java

/**
 * ?/*from w w  w.  j  a  va  2s .com*/
 * 
 * @param request
 * @return
 */
@RequestMapping("uploadImage")
@ResponseBody()
public void uploadImage(MultipartHttpServletRequest request) {
    try {
        AppUser curUser = App.current().getUser();
        User user = userInfoService.findByUserId(curUser.getId());
        String label = request.getParameter("label");
        MultipartFile file = request.getFile("file");
        String imgStr = Images.toBase64(Files.getMimeType(file.getOriginalFilename()), file.getBytes());
        userInfoService.saveImage(user, imgStr, com.jlfex.hermes.model.UserImage.Type.AUTH, label);
    } catch (Exception e) {
        Logger.error(e.getMessage(), e);
        throw new ServiceException(e.getMessage(), e);
    }
}

From source file:controllers.SequenceController.java

@RequestMapping("/updateFromXml")
public String updateFromXml(Map<String, Object> model,
        @RequestParam(value = "xlsFile", required = false) MultipartFile file,
        @RequestParam(value = "sequenceId", required = true) Long sequenceId, RedirectAttributes ras) {
    if (file == null || file.isEmpty()) {
        ras.addFlashAttribute("error", "File not found");
    } else {// w  w w.  ja  va 2  s  . co m
        File newFile = new File("/usr/local/etc/sceneParamsList");
        if (newFile.exists()) {
            newFile.delete();
        }
        try {
            FileUtils.writeByteArrayToFile(newFile, file.getBytes());
            sequenceService.updateFromXml(newFile, sequenceId);
            ras.addFlashAttribute("error", sequenceService.getResult().getErrors());
        } catch (Exception e) {
            ras.addFlashAttribute("error",
                    "updateFromXml" + StringAdapter.getStackTraceException(e)/*e.getMessage()*/);
        }
        if (newFile.exists()) {
            newFile.delete();
        }
    }
    ras.addAttribute("sequenceId", sequenceId);
    return "redirect:/Sequence/showOne";
}

From source file:org.literacyapp.web.content.multimedia.audio.AudioCreateController.java

@RequestMapping(method = RequestMethod.POST)
public String handleSubmit(HttpSession session, /*@Valid*/ Audio audio,
        @RequestParam("bytes") MultipartFile multipartFile, BindingResult result, Model model) {
    logger.info("handleSubmit");

    if (StringUtils.isBlank(audio.getTranscription())) {
        result.rejectValue("transcription", "NotNull");
    } else {/*from w w  w .java 2s  . c  om*/
        Audio existingAudio = audioDao.read(audio.getTranscription(), audio.getLocale());
        if (existingAudio != null) {
            result.rejectValue("transcription", "NonUnique");
        }
    }

    try {
        byte[] bytes = multipartFile.getBytes();
        if (multipartFile.isEmpty() || (bytes == null) || (bytes.length == 0)) {
            result.rejectValue("bytes", "NotNull");
        } else {
            String originalFileName = multipartFile.getOriginalFilename();
            logger.info("originalFileName: " + originalFileName);
            if (originalFileName.toLowerCase().endsWith(".mp3")) {
                audio.setAudioFormat(AudioFormat.MP3);
            } else if (originalFileName.toLowerCase().endsWith(".ogg")) {
                audio.setAudioFormat(AudioFormat.OGG);
            } else if (originalFileName.toLowerCase().endsWith(".wav")) {
                audio.setAudioFormat(AudioFormat.WAV);
            } else {
                result.rejectValue("bytes", "typeMismatch");
            }

            if (audio.getAudioFormat() != null) {
                String contentType = multipartFile.getContentType();
                logger.info("contentType: " + contentType);
                audio.setContentType(contentType);

                audio.setBytes(bytes);

                // TODO: convert to a default audio format?
            }
        }
    } catch (IOException e) {
        logger.error(e);
    }

    if (result.hasErrors()) {
        model.addAttribute("contentLicenses", ContentLicense.values());

        model.addAttribute("literacySkills", LiteracySkill.values());
        model.addAttribute("numeracySkills", NumeracySkill.values());

        return "content/multimedia/audio/create";
    } else {
        audio.setTranscription(audio.getTranscription().toLowerCase());
        audio.setTimeLastUpdate(Calendar.getInstance());
        audioDao.create(audio);

        Contributor contributor = (Contributor) session.getAttribute("contributor");

        ContentCreationEvent contentCreationEvent = new ContentCreationEvent();
        contentCreationEvent.setContributor(contributor);
        contentCreationEvent.setContent(audio);
        contentCreationEvent.setCalendar(Calendar.getInstance());
        contentCreationEventDao.create(contentCreationEvent);

        if (EnvironmentContextLoaderListener.env == Environment.PROD) {
            String text = URLEncoder.encode(contributor.getFirstName() + " just added a new Audio:\n"
                    + " Language: " + audio.getLocale().getLanguage() + "\n" + " Transcription: \""
                    + audio.getTranscription() + "\"\n" + " Audio format: " + audio.getAudioFormat() + "\n"
                    + "See ") + "http://literacyapp.org/content/multimedia/audio/list";
            String iconUrl = contributor.getImageUrl();
            SlackApiHelper.postMessage(Team.CONTENT_CREATION, text, iconUrl, "http://literacyapp.org/audio/"
                    + audio.getId() + "." + audio.getAudioFormat().toString().toLowerCase());
        }

        return "redirect:/content/multimedia/audio/list";
    }
}

From source file:it.geosolutions.opensdi2.service.impl.FileUploadServiceImpl.java

/**
 * Get a file from a single multipart file
 * /*from  w w  w  .  jav  a2 s  .  c om*/
 * @param file
 * @param filePath
 * @throws IOException if something occur while file generation
 */
public File getCompletedFile(MultipartFile file, String filePath) throws IOException {
    File outFile = new File(filePath);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Writing complete content to " + filePath);
    }
    OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outFile));
    for (byte b : file.getBytes()) {
        outputStream.write(b);
        outputStream.flush();
    }
    outputStream.close();
    return outFile;
}

From source file:de.metas.ui.web.window.controller.WindowRestController.java

/**
 * Attaches a file to given root document.
 *
 * @param adWindowId/*from  w w w .j av  a 2s . c o  m*/
 * @param documentId
 * @param file
 * @throws IOException
 */
@PostMapping("/{windowId}/{documentId}/attachments")
public void attachFile(@PathVariable("windowId") final int adWindowId //
        , @PathVariable("documentId") final String documentId //
        , @RequestParam("file") final MultipartFile file //
) throws IOException {
    userSession.assertLoggedIn();

    final String name = file.getOriginalFilename();
    final byte[] data = file.getBytes();

    final DocumentPath documentPath = DocumentPath.rootDocumentPath(DocumentType.Window, adWindowId,
            documentId);
    final Document document = documentCollection.getDocument(documentPath);

    Services.get(IAttachmentBL.class).createAttachment(document, name, data);
}

From source file:org.literacyapp.web.content.multimedia.image.ImageCreateController.java

@RequestMapping(method = RequestMethod.POST)
public String handleSubmit(HttpSession session, /*@Valid*/ Image image,
        @RequestParam("bytes") MultipartFile multipartFile, BindingResult result, Model model) {
    logger.info("handleSubmit");

    if (StringUtils.isBlank(image.getTitle())) {
        result.rejectValue("title", "NotNull");
    } else {/*from ww  w.j a  v  a2  s.  c  o  m*/
        Image existingImage = imageDao.read(image.getTitle(), image.getLocale());
        if (existingImage != null) {
            result.rejectValue("title", "NonUnique");
        }
    }

    try {
        byte[] bytes = multipartFile.getBytes();
        if (multipartFile.isEmpty() || (bytes == null) || (bytes.length == 0)) {
            result.rejectValue("bytes", "NotNull");
        } else {
            String originalFileName = multipartFile.getOriginalFilename();
            logger.info("originalFileName: " + originalFileName);
            if (originalFileName.toLowerCase().endsWith(".png")) {
                image.setImageFormat(ImageFormat.PNG);
            } else if (originalFileName.toLowerCase().endsWith(".jpg")
                    || originalFileName.toLowerCase().endsWith(".jpeg")) {
                image.setImageFormat(ImageFormat.JPG);
            } else if (originalFileName.toLowerCase().endsWith(".gif")) {
                image.setImageFormat(ImageFormat.GIF);
            } else {
                result.rejectValue("bytes", "typeMismatch");
            }

            if (image.getImageFormat() != null) {
                String contentType = multipartFile.getContentType();
                logger.info("contentType: " + contentType);
                image.setContentType(contentType);

                image.setBytes(bytes);

                if (image.getImageFormat() != ImageFormat.GIF) {
                    int width = ImageHelper.getWidth(bytes);
                    logger.info("width: " + width + "px");

                    if (width < ImageHelper.MINIMUM_WIDTH) {
                        result.rejectValue("bytes", "image.too.small");
                        image.setBytes(null);
                    } else {
                        if (width > ImageHelper.MINIMUM_WIDTH) {
                            bytes = ImageHelper.scaleImage(bytes, ImageHelper.MINIMUM_WIDTH);
                            image.setBytes(bytes);
                        }
                    }
                }
            }
        }
    } catch (IOException e) {
        logger.error(e);
    }

    if (result.hasErrors()) {
        model.addAttribute("contentLicenses", ContentLicense.values());
        model.addAttribute("literacySkills", LiteracySkill.values());
        model.addAttribute("numeracySkills", NumeracySkill.values());
        return "content/multimedia/image/create";
    } else {
        image.setTitle(image.getTitle().toLowerCase());
        int[] dominantColor = ImageColorHelper.getDominantColor(image.getBytes());
        image.setDominantColor(
                "rgb(" + dominantColor[0] + "," + dominantColor[1] + "," + dominantColor[2] + ")");
        image.setTimeLastUpdate(Calendar.getInstance());
        imageDao.create(image);

        Contributor contributor = (Contributor) session.getAttribute("contributor");

        ContentCreationEvent contentCreationEvent = new ContentCreationEvent();
        contentCreationEvent.setContributor(contributor);
        contentCreationEvent.setContent(image);
        contentCreationEvent.setCalendar(Calendar.getInstance());
        contentCreationEventDao.create(contentCreationEvent);

        if (EnvironmentContextLoaderListener.env == Environment.PROD) {
            String text = URLEncoder
                    .encode(contributor.getFirstName() + " just added a new Image:\n" + " Language: "
                            + image.getLocale().getLanguage() + "\n" + " Title: \"" + image.getTitle()
                            + "\"\n" + " Image format: " + image.getImageFormat() + "\n" + "See ")
                    + "http://literacyapp.org/content/multimedia/image/list";
            String iconUrl = contributor.getImageUrl();
            SlackApiHelper.postMessage(Team.CONTENT_CREATION, text, iconUrl, "http://literacyapp.org/image/"
                    + image.getId() + "." + image.getImageFormat().toString().toLowerCase());
        }

        return "redirect:/content/multimedia/image/list";
    }
}

From source file:com.oakhole.sms.web.SmsTaskController.java

@ResponseBody
@RequestMapping(value = "uploadPhoneFile")
public String uploadPhoneFile(@RequestParam(value = "fileupload", required = false) MultipartFile fileupload) {
    //        // todo: ?json?
    //        try {
    //            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileupload.getInputStream()));
    //        } catch (IOException e) {
    //            e.printStackTrace();
    //            return "fail: " + e.getMessage();
    //        }/*  ww w .  ja v a  2 s  . c om*/

    String phoneNumbers = "";

    try {
        phoneNumbers = String.valueOf(fileupload.getBytes());
    } catch (IOException e) {
        e.printStackTrace();
        return "fail: " + e.getMessage();
    }
    return "success: " + phoneNumbers;
}

From source file:it.geosolutions.opensdi.service.impl.FileUploadServiceImpl.java

/**
 * Get a file from a single multipart file
 * /*  w w w. j  a v  a 2s.  co m*/
 * @param name of the file
 * @param file with the content uploaded
 * @return File
 * @throws IOException if something occur while file generation
 */
public File getCompletedFile(String name, MultipartFile file) throws IOException {
    String filePath = temporaryFolder + File.separator + name;
    File outFile = new File(filePath);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Writing complete content to " + filePath);
    }
    OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outFile));
    for (byte b : file.getBytes()) {
        outputStream.write(b);
        outputStream.flush();
    }
    outputStream.close();
    return outFile;
}